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.

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

With all due respect I have my doubt about your answer. Constructor injection is possible.
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.
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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.