Spring
Spring

Reputation: 11835

Spring: How to autowire or (use new) a bean with constructor parameter and which is not a managed bean

There are many similar questions here but none showing how to do it. Here, how can I autowire CreateDatabaseAction bean and use it? It expects a Shoppingcart object, and it is NOT a spring managed bean. Or do I have to create it with new keyword?

public abstract class AbstractServiceActions {
  @Autowired
  protected DatabaseModel dbModel;

  protected User user;

  public AbstractServiceActions(ShopingCart cart) {
     this.user = user;
 }

And implement it:

@Component
 public class CreateDatabaseAction extends AbstractServiceActions {
      public CreateDatabaseAction(ShoppingCArt cart){
            super(cart);
      }

 }

Upvotes: 1

Views: 281

Answers (1)

tibtof
tibtof

Reputation: 7957

There's no way for Spring to know what ShoppingCart instance to use when instantiating CreateDatabaseAction if there is no managed bean of that type. I think that you should reconsider the design. For example send it as method parameter where it's actually used and remove it from the constructor.

Considering only the names, I would say that ShoppingCart would be a good candidate for a session scoped bean.

Upvotes: 4

Related Questions