我正在使用Spring Boot注释配置。我有一个其构造函数接受2个参数(字符串,另一个类)的类。
水果.java
public class Fruit { public Fruit(String FruitType, Apple apple) { this.FruitType = FruitType; this.apple = apple; } }
苹果.java
public class Apple { }
我有一个需要通过将参数注入构造函数来自动装配上述类的类(“铁果”,Apple类)
库克
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注释的用法。
@Autowired
@Value
库克也应该有@Component。
@Component
更新资料
或者您可以使用@Configuration和@Bean注释:
@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()); } ... }