Can*_*uck 0 java spring dependency-injection javabeans autowired
如果我的ApplicationContext中有2个bean实现相同的接口,我可以在bean定义中将其中一个标记为primary.这个bean更适合依赖注入.
有没有办法使用ApplicationContext直接访问主要的没有DI?
有很多不同的方法可以做到这一点.
在主bean定义中设置primary ="true".设置此项后,如果有多个自动接线的候选项,则将为主站提供更高的优先级.
<beans ...>
<bean id="myPrimaryBeanId" class="mypackage.MyInterface" primary="true"/>
<bean id="mySecondaryBeanId" class="mypackage.MyInterface" />
</beans>
Run Code Online (Sandbox Code Playgroud)或者,如果您认为此bean不应自动连接到任何bean,则为非主Bean设置autowire-candidate ="false".但是,在定义具有相同接口的另一个bean时需要小心,就好像忘记添加它一样,将会有多个主bean.
<beans ...>
<bean id="myPrimaryBeanId" class="mypackage.MyInterface"/>
<bean id="mySecondaryBeanId" class="mypackage.MyInterface"
autowire-candidate="false"/>
</beans>
Run Code Online (Sandbox Code Playgroud)通过使用命名依赖项更加具体地说明自动布线注释,可以使用@javax.annotation.Resource注释来存档,如下所示.这将减少确定可以注入哪个bean的代码复杂性,因为可以简单地通过id定位bean.
@Resource(name="myPrimaryBeanId")
protected MyInterface myInstance;
Run Code Online (Sandbox Code Playgroud)非依赖注入(DI)方法
如果您不想使用DI,可以使用以下命令从ApplicationContext中按名称获取bean
MyInterface myInstance = (MyInterface)
applicationContext.getBean("myPrimaryBeanId");
Run Code Online (Sandbox Code Playgroud)
如果你想使用非DI方法,但是从spring bean开始,如果你没有弹簧上下文的句柄来做,你可以改变你的类来实现org.springframework.context.ApplicationContextAware接口,将要求您实现setApplicationContext(ApplicationContext)方法,spring将把句柄注入当前应用程序上下文,如下所示.
public class MyBean implements ApplicationContextAware {
private ApplicationContext applicationContext;
private String MY_PRIMARY_BEAN_ID = "myPrimaryBeanId";
public void myMethod() {
MyInterface myInstance = getMyPrimaryBean();
// do my logic here
}
private MyInterface getMyPrimaryBean() {
return (MyInterface) applicationContext.getBean(MY_PRIMARY_BEAN_ID);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.applicationContext = applicationContext;
}
}
Run Code Online (Sandbox Code Playgroud)
注意:此答案基于Spring 2.5.x.
| 归档时间: |
|
| 查看次数: |
5308 次 |
| 最近记录: |