简体   繁体   English

春季:如何使用构造函数参数(不是托管bean)自动装配或(使用新的)bean

[英]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? 在这里,我如何自动连接CreateDatabaseAction bean并使用它? It expects a Shoppingcart object, and it is NOT a spring managed bean. 它需要一个Shoppingcart对象,并且不是Spring托管的bean。 Or do I have to create it with new keyword? 还是我必须使用new关键字创建它?

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);
      }

 }

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. 如果没有该类型的托管Bean,Spring将无法知道在实例化CreateDatabaseAction时使用哪个ShoppingCart实例。 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. 仅考虑名称,我想说ShoppingCart将是会话范围的Bean的理想选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM