我使用的是Spring Boot注解配置。我有一个类,它的构造函数接受2个参数(string,另一个类)。
Fruit.java
public class Fruit {
public Fruit(String FruitType, Apple apple) {
this.FruitType = FruitType;
this.apple = apple;
}
}Apple.java
public class Apple {
}我有一个类,它需要通过向构造函数(“iron Fruit",Apple类)注入参数来自动绑定上面的类。
Cook.java
public class Cook {
@Autowired
Fruit applefruit;
}厨师类需要使用参数自动连接Fruit类(“iron Fruit",Apple类)
XML配置如下所示:
<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>如何仅使用注释配置来实现它?
发布于 2015-05-29 22:53:36
Apple必须是spring管理的bean:
@Component
public class Apple{
}水果也是如此:
@Component
public class Fruit {
@Autowired
public Fruit(
@Value("iron Fruit") String FruitType,
Apple apple
) {
this.FruitType = FruitType;
this.apple = apple;
}
}注意@Autowired和@Value注释的用法。
库克也应该有@Component。
更新
或者,您可以使用@Configuration和@Bean注释:
@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());
}
...
}https://stackoverflow.com/questions/30532459
复制相似问题