代码之家  ›  专栏  ›  技术社区  ›  Chirag Arora

如何在构造函数中使用注入的依赖关系?

  •  0
  • Chirag Arora  · 技术社区  · 5 月前

    我有一个Spring组件,我在其中注入了依赖项(其他组件),但我无法在构造函数中使用这些注入的依赖项 null 在调用构造函数时。是否有方法在构造函数中使用这些依赖关系?

    @Component
    @RequestScope
    public class MyComponent {
    
        @Inject
        OtherComponent1 otherComponent1
    
        @Inject
        OtherComponent2 otherComponent2
    
        MyComponent() {
            otherComponent1.someMethod(); // null
            otherComponent2.someMethod(); // null
        }
    }
    
    1 回复  |  直到 5 月前
        1
  •  1
  •   June    5 月前

    Spring中有两种注入方法:属性注入(如您所使用的)和构造函数注入。对于属性注入,Spring bean工厂将使用其 默认构造函数 ( MyComponent )(这就是为什么你需要默认构造函数 @Component 带注释的类),然后Spring框架将注入 OtherComponent1 OtherComponent2 在它们完全构建(注入所有依赖项)之后。因此,当 MyComponent() 被调用时,属性 otherComponent1 otherComponent2 只是将普通属性初始化为 null 。要使用这些依赖关系,您应该使用构造函数注入。 代码如下:

    @Component
    @RequestScope
    public class MyComponent {
        OtherComponent1 otherComponent1
        OtherComponent2 otherComponent2
    
        MyComponent(OtherComponent1 otherComponent1, OtherComponent2 otherComponent2) {
            this.otherComponent1 = otherComponent1;
            this.otherComponent2 = otherComponent2;
            this.otherComponent1.someMethod(); // call methods ok
            this.otherComponent2.someMethod(); // call methods ok
        }
    }