简体   繁体   中英

Spring register bean in runtime

I would like to register spring bean in runtime, so i built that class:

public class SpringBeanRegister implements BeanRegister, ApplicationContextAware {

    private ConfigurableApplicationContext context;

    public void registerBean(Object object) {
        ConfigurableListableBeanFactory factory = context.getBeanFactory();
        factory.registerSingleton("beanName", object);
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = (ConfigurableApplicationContext) applicationContext; // -- safe?
    } 

}

is this cast always safe ?

At the moment (Spring 4.1) there is only implementation of ApplicationContext that does not implement the ConfigurableApplicationContext interface: that is org.springframework.test.web.servlet.setup.StubWebApplicationContext from spring-test

So I think you are relative save and need to pay some attention to the tests.

But just because there is no meaningful implementation at the moment, it does not mean that there is no change in future version, or somebody/some Framework has implemented it already!

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