在 Spring 中通过注释向构造函数注入参数
Inject parameters to constructor through annotation in Spring
我正在使用 Spring 引导注释配置。我有一个 class 其构造函数接受 2 个参数(字符串,另一个 class)。
Fruit.java
public class Fruit {
public Fruit(String FruitType, Apple apple) {
this.FruitType = FruitType;
this.apple = apple;
}
}
Apple.java
public class Apple {
}
我有一个 class 需要通过向构造函数注入参数来自动装配上述 class("iron Fruit",Apple class)
Cook.java
public class Cook {
@Autowired
Fruit applefruit;
}
厨师class需要使用参数自动装配水果class("iron Fruit",苹果class)
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>
如何只使用注解配置来实现?
Apple 必须是 spring-managed 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());
}
...
}
我正在使用 Spring 引导注释配置。我有一个 class 其构造函数接受 2 个参数(字符串,另一个 class)。
Fruit.java
public class Fruit {
public Fruit(String FruitType, Apple apple) {
this.FruitType = FruitType;
this.apple = apple;
}
}
Apple.java
public class Apple {
}
我有一个 class 需要通过向构造函数注入参数来自动装配上述 class("iron Fruit",Apple class)
Cook.java
public class Cook {
@Autowired
Fruit applefruit;
}
厨师class需要使用参数自动装配水果class("iron Fruit",苹果class)
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>
如何只使用注解配置来实现?
Apple 必须是 spring-managed 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());
}
...
}