我有以下情况。
我有两个豆子,例如:
<bean id="service1" parent="txProxyTemplate">
<property name="target">
<bean autowire="byName" class="Class1"/>
</property>
</bean>
<bean name="manager1" parent="txProxyServiceTemplate">
<property name="target">
<bean autowire="byName" class="ManagerClass1"/
</property>
</bean>
我有第三个豆子,真正注入这两个baens:
<bean name="supportBean" parent="txProxyServiceTemplate">
<property name="target">
<bean autowire="byName" class="SupportBeanClass">
</bean>
</property>
</bean>
bean service1(path =“first path”)和manager1(path =“second path”)中有字符串“path”字段。 当supportBean被注入service1和manager1时,我希望supportBean中的一些字符串字段(例如“actualPath”)是从两个封闭的bean自动启动的。我怎么能在春天这样做?
PS:我需要service1和manager1有两个不同字段的supportBean(在service1类supportBean中有actualPath =“第一个路径”,在manager1类supportBean中有actualPath =“第二个路径”我希望你理解我,谢谢!
答案 0 :(得分:1)
如果没有看到任何实际代码,您是否可以在封闭bean的setter中的actualPath
上设置SupportBean
? SupportBean
需要具有原型范围,以便可以维持单独的状态。
例如,如果您的SupportBean
看起来像这样:
@Component
@Scope("prototype")
public class SupportBean {
private String actualPath;
public void setActualPath(String actualPath) {
this.actualPath = actualPath
}
}
然后,您可以在封闭bean的setter中的SupportBean
上设置实际路径。所以Service1
可能看起来像这样:
@Service
public class Service1 {
private String path = "first path";
private SupportBean supportBean;
@Autowired
public void setSupportBean(SupportBean supportBean) {
this.supportBean = supportBean;
this.supportBean.setActualPath(this.path);
}
}
Manager1
就像这样:
@Service
public class Manager1 {
private String path = "second path";
private SupportBean supportBean;
@Autowired
public void setSupportBean(SupportBean supportBean) {
this.supportBean = supportBean;
this.supportBean.setActualPath(this.path);
}
}
如果你更愿意使用构造函数注入,那么只需删除setter并自动装配构造函数:
@Service
public class Service1 {
private String path = "first path";
private SupportBean supportBean;
@Autowired
public Service1(SupportBean supportBean) {
this.supportBean = supportBean;
this.supportBean.setActualPath(this.path);
}
}