开发者

compile time weaving and autowired on constructor

开发者 https://www.devze.com 2023-02-03 10:48 出处:网络
@Configurable public TestClass(){ @Autowired SomeOtherClass otherClass; public TestClass(Var1 var){ System.out.println(otherClass);
@Configurable
public TestClass(){

@Autowired SomeOtherClass otherClass;

public TestClass(Var1 var){

System.out.println(otherClass);

}


}

I using compile time weaving and call new testClass(var). i using dependency injection on t开发者_如何转开发he constructor like above "otherClass". It printed out 'null'. From my test, dependency injection 'otherClass' cannot be initialized in constructor. what should i do to allow dependency injection on "constructor" ?


Look at the Note in this section of the Spring documentation.

It shows you the @Configurable attribute to use to force the injection before the code within the constructor.

@Configurable(preConstruction=true)

Adding that attribute to your code above will stop the System.out.println(otherClass); from being null.


In support of the answer by Ralph.

From the Spring Autowired documentation.

Fields are injected right after construction of a bean, before any config methods are invoked.

HTH


I guess (but don't know 100%) that the Autowirering take place after the object is created. (I mean I know it for normal Spring Beans, for normal classes, but not 100% for @Configurable)

This mean you can not expect to have an Autowired field allready populated when the object is created.

You can check this if you add an second method printStats that is invoked after creation.

public class TestClass {
  ...
   public void printStats(){
     System.out.println(otherClass);
   }
}

...
new TestClass(var).printStats();
0

精彩评论

暂无评论...
验证码 换一张
取 消