4

I'm using @Value annotation to fetch properties & it is happening successfully in Normal method but not in Class constructor.Can anyone tell what may be the reason?

Class A {

    @Value("#{columnProperties['Users.Columns']}")
    String columnNames;

    A()
    {
        System.out.println("In Constructor="+columnNames);
    }

    void show()
    {
        System.out.println("In Method="+columnNames);
    }

}

when i do

A obj=new A();

i get the output

In Constructor=null

and obj.show() gives

In Method=A,B,C

(that means desired result)

I want values to be set as soon as constructor is called.I'm getting compilation error if i put the String declaration in static or initialize block.

Brian Roach
  • 76,169
  • 12
  • 136
  • 161
  • may be a duplicates of http://stackoverflow.com/questions/2306078/spring-constructor-injection-of-primitive-values-properties-with-annotation-ba –  Sep 15 '11 at 05:43

2 Answers2

3

How can we be sure that a member of an object is truly ready when the object is not finished being constructed (that is, the objects constructor is still not finshed)? It seems likely to me that Spring will not inject that value until AFTER the constructor has finished.

nicholas.hauschild
  • 42,483
  • 9
  • 127
  • 120
  • With all due respect I have my doubt about your answer. Constructor injection is possible. – Shahzeb Sep 15 '11 at 07:13
  • You can definitely do _Constructor Injection_ with Spring, but that isn't what you are doing above. Nicholas is correct in suggesting that the constructor is going to execute (and complete) first, then Spring will do the injection. If you want _constructor injection_, you will need to declare an input parameter to the constructor. See [this](http://stackoverflow.com/questions/2306078/spring-constructor-injection-of-primitive-values-properties-with-annotation-ba). – AWhitford Sep 15 '11 at 08:15
  • Yes, as @AWhitford suggests, Constructor Injection requires a parameter to be passed in. What is happening in the question is not constructor injection, but setter injection, which happens after an object is created, which is after the constructor is finished executing. – nicholas.hauschild Sep 15 '11 at 12:10
3

nicholas.hauschild is correct. The @Value will be injected after the object is constructed. If you want to do some initialization after the bean is constructed then you should implement IntializingBean.

sourcedelica
  • 23,940
  • 7
  • 66
  • 74