Search code examples
javaspringdependency-injectionspring-annotationsconstructorargument

How do I perform Constructor-based dependency injection with Spring using annotations?


OK, so if I need to put some primitive values in the constructor, how do I do that?

    @Autowired
public CustomBean(String name, @Qualifier("SuperBean") SuperBean superBean) {
    super();
    this.superBean = superBean;
    this.name = name;
}

For instance here I am defining that the superBean has the Qualifier "SuperBean", but I'd also like to know how is it possible to use annotations to set the name value here?

I know it's possible with xml configuration, but I want to know how to do this with annotations too:

<bean id="CustomXmlBean" class="org.arturas.summerfav.beans.CustomXmlBean">
        <constructor-arg name="name" type="String" value="The Big Custom XML Bean" />
        <constructor-arg>
            <bean id="SuperBean" class="org.arturas.summerfav.beans.SuperBean" />
        </constructor-arg>
    </bean>

Well how do I put in values for String, int and other generic types?


Solution

  • Here is one way to do this:

    @Component 
    public class YourBean { 
        @Autowired
        public YourBean(@Value("${prop1}") String arg1, @Value("${prop2}") String arg2) { 
            // rest of the code
        } 
    }