在Spring中通过注释向构造函数注入参数
问题描述:
我正在使用Spring Boot注释配置。我有一个类的构造函数接受2个参数(字符串,另一个类)。在Spring中通过注释向构造函数注入参数
Fruit.java
public class Fruit {
public Fruit(String FruitType, Apple apple) {
this.FruitType = FruitType;
this.apple = apple;
}
}
Apple.java
public class Apple {
}
予有需要通过注入参数,以构造自动装配上述类的类( “铁果”,苹果类)
Cook.java
public class Cook {
@Autowired
Fruit applefruit;
}
厨师类需要自动装配水果类参数(“铁果”,苹果类)
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>
如何只用注释配置实现的呢?
答
苹果必须是春季管理的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());
}
...
}
我提高了我的问题有点。 如果我需要注射不同的苹果(红苹果或青苹果),该怎么做。 不同的同类豆。 Fruit class构造函数参数必须注入redapple或greenapple – vishnumanohar
@vishnumanohar更新了我的答案。 – medvedev1088
如果Apple没有进行弹簧管理并且无法修改第三方库,该怎么办? – Claus