简体   繁体   English

我可以在运行时更改spring注入的实现类吗?

[英]Can I change the implementation class injected by spring in runtime?

I have a class has injected by spring on the applicationContext.xml and I need change that implementation without change the applicationContext.xml. 我有一个类已在spring之前注入到applicationContext.xml上,我需要在不更改applicationContext.xml的情况下更改该实现。

I heard about AOP "IntroductionInterceptor" but I don't found many useful results. 我听说过AOP“ IntroductionInterceptor”,但没有发现很多有用的结果。

Anyone can help me? 有人可以帮助我吗?

PS. PS。 Sorry my bad english, hope that give to understand. 对不起,我英语不好,希望能给理解。

One way to tackle is, is to apply the service locator pattern . 解决的方法之一是应用服务定位器模式 Instead of injecting the bean directly, you inject a ServiceLocator which can return different implementation. 代替直接注入bean,可以注入ServiceLocator,它可以返回不同的实现。

//ServiceLocator bean
public Class ServiceLocator {

    @Resource(name="service1")
    private Service service1;

    @Resource(name="service1")
    private Service Service2;

    public Service getService(String service) {
       return ... //service
    }
}

You can do this in several ways, here are few: 您可以通过多种方式进行操作,以下几种方式:

  1. Write an xml file, override configuration by adding same bean id and the implementation class that you want to use, import this new xml into your existing application context. 编写一个xml文件,通过添加相同的bean id和要使用的实现类来覆盖配置,然后将这个新的xml导入到您现有的应用程序上下文中。

  2. Through code, base on your need you can set a new implementation before calling the code. 通过代码,您可以根据需要在调用代码之前设置新的实现。

There could be more but mostly we have used '1' in number of projects. 可能会有更多,但大多数情况下,我们在项目数量中使用了“ 1”。

If you have multiple beans with same id, spring will pickup latest one, eg 如果您有多个具有相同id的bean,spring将会获取最新的id,例如

<beans>
   <import resource="a.xml"/>
   <import resource="b.xml"/>
</beans>

Now if both a.xml and b.xml have a bean defined with same Id, spring will use the bean defined in b.xml . 现在,如果a.xmlb.xml都具有使用相同ID定义的bean,spring将使用b.xml定义的bean。

Cheers !! 干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM