Inject parameters to constructor through annotation in Spring -


i using spring boot annotation configuration. have class constructor accepts 2 parameters (string, class).

fruit.java

public class fruit {     public fruit(string fruittype, apple apple) {             this.fruittype = fruittype;             this.apple = apple;         } } 

apple.java

public class apple {  } 

i have class needs autowire above class injecting parameters constructor("iron fruit",apple class)

cook.java

public class cook {      @autowired     fruit applefruit; } 

the cook class need autowire fruit class parameters("iron fruit",apple class)

the xml configuration looks this:

<bean id="redapple" class="apple" /> <bean id="greenapple" class="apple" /> <bean name="applecook" class="cook">           <constructor-arg index="0" value="iron fruit"/>           <constructor-arg index="1" ref="redapple"/> </bean> <bean name="applecook2" class="cook">           <constructor-arg index="0" value="iron fruit"/>           <constructor-arg index="1" ref="greenapple"/> </bean> 

how achieve using annotation configuration only?

apple must spring-managed bean:

@component public class apple{  } 

fruit well:

@component public class fruit {      @autowired     public fruit(         @value("iron fruit") string fruittype,         apple apple         ) {             this.fruittype = fruittype;             this.apple = apple;         } } 

note usage of @autowired , @value annotations.

cook should have @component too.

update

or use @configuration , @bean annotations:

@configuration  public class config {      @bean(name = "redapple")     public apple redapple() {         return new apple();     }      @bean(name = "greeapple")     public apple greenapple() {         retturn new apple();     }      @bean(name = "applecook")     public cook applecook() {         return new cook("iron fruit", redapple());     }     ... } 

Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -