当前位置: 动力学知识库 > 问答 > 编程问答 >

java - compile time weaving and autowired on constructor

问题描述:

@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 the 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" ?

网友答案:

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();
网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: