我在将xml中的bean引用转换为java config时遇到问题。在XML中我有类似的东西:
<bean id="user" com="User">
<constructor-arg name="pFirst" value="first" />
<constructor-arg name="pSecond" value="second" />
<constructor-arg name="pThird" value="third" />
</bean>
<bean id="department" com="Department">
<constructor-arg name="pfourth" value="fourth" />
<constructor-arg name="pFifth" value="fifth" />
<constructor-arg ref="user" />
</bean>
在java配置中,我现在有了这个:
@Bean
@Autowired
public User user(First first, Second second, Third third)
{
return new User(first, second, third);
}
@Bean
@Autowired
public Department department(First first, Second second, Third third, Fourth fourth, Fifth fifth)
{
return new Department(fourth, fifth, user(first, second, third));
}
我不想像对待用户那样将相同的参数传递给部门。在XML中,我可以引用用户bean并在没有其他参数的情况下使用它。我怎么能在java配置文件中这样做。我希望java配置文件看起来如下所示:
@Bean
@Autowired
public User user(First first, Second second, Third third)
{
return new User(first, second, third);
}
@Bean
@Autowired
public Department department(Fourth fourth, Fifth fifth, User user)
{
return new Department(fourth, fifth, user);
}
这个使用先前定义的bean作为第三个参数,但我不能得到这样的东西。
我如何将User bean作为构造函数的一部分引用到另一个bean?
答案 0 :(得分:2)
@Bean
public User user() {
return new User("first", "second", "third");
}
@Bean
public Department department() {
return new Department("fourth", "fifth", user());
}
现在,您可以在容器中的其他类中使用@Autowired
并注入您的用户或部门(例如在控制器中)
@Autowired
private User user; // will return the user from the user() java config defined bean
答案 1 :(得分:0)
首先,@Bean
方法通常不应注释@Autowired
;应该应用于包含bean的@Configuration
对象上的字段。
@Configuration
public class MyConfig {
@Autowired First first;
@Autowired Second second;
@Autowired Third third;
@Bean public User user() {
return new User(first, second, third);
}
@Autowired Fourth fourth;
@Autowired Fifth fifth;
@Bean public Department department() {
// call to user() is magically proxied to apply Spring bean scope
return new Department(fourth, fifth, user());
}
}
这通常足以让Spring处理适当的依赖项。在存在歧义或其他困难的奇怪情况下,您可以使用嵌套配置类:
@Configuration
public class MyConfig {
@Autowired First first;
@Autowired Second second;
@Autowired Third third;
@Bean public User user() {
return new User(first, second, third);
}
@Configuration
public static class MySubConfig {
@Autowired Fourth fourth;
@Autowired Fifth fifth;
@Autowired User user;
@Bean public Department department() {
return new Department(fourth, fifth, user);
}
}
}