简体   繁体   中英

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.

I heard about AOP "IntroductionInterceptor" but I don't found many useful results.

Anyone can help me?

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.

//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.

  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.

If you have multiple beans with same id, spring will pickup latest one, eg

<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 .

Cheers !!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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