AnnotationConfigApplicationContext寄存器&刷新另一个配置类

时间:2015-04-08 09:40:34

标签: java spring

我正在使用配置类(mock)初始化服务定位器(Singleton)中的AnnotationConfigApplicationContext(register + refresh)。

当我启动应用程序时,我设置了一个配置类属性。我想替换已注册的配置类并重新加载我的配置。

由于“刷新”方法可以使用一次,是否可以或者我可以直接在init设置正确的配置类?

Config class 1

@Configuration
@ComponentScan(basePackages = { "com.xxx.core.service.ws.controller" })
@EnableWebMvc
public class ContextCoreMockConfiguration {
}

Config class 2

@Configuration
@EnableTransactionManagement
@ImportResource(value={ "classpath:sessionFactory-datasource-spring.xml"} )
@ComponentScan(basePackages = { "com.xxx.core.service.impl"
                              , "com.xxx.core.dao.impl" })
public class ContextCoreServiceConfiguration {
}

单身初始化上下文

public class AnnotationContextCoreLocator { 
    private AnnotationConfigApplicationContext  context; // Context IOC

    private AnnotationContextCoreLocator() {
        this.context = new AnnotationConfigApplicationContext();
        this.context.register(ContextCoreMockConfiguration.class);
        this.context.refresh();
    }


    /**
     * Context
     * @return AnnotationConfigApplicationContext
     */
    public static AnnotationConfigApplicationContext  getInstance() {
        return SingletonHolder.INSTANCE.getContext();
    }

    /**
     * singleton instanciation
     * @author asi
     *
     */
    private static class SingletonHolder {
        static final AnnotationContextCoreLocator INSTANCE = new AnnotationContextCoreLocator();
    }

    private AnnotationConfigApplicationContext  getContext() {
        return context;
    }
}

我们的想法是在运行时能够更改Singleton的配置类

String configCoreClass = servlet.getInitParameter("contextCoreConfigurationClass");
AnnotationContextCoreLocator.getInstance().register( Class.forName(configCoreClass) );
AnnotationContextCoreLocator.getInstance().refresh();

问题是“刷新”方法可以使用一次。我可以从我的Singleton中删除“刷新”,并在第一次使用时进行,但我想在运行时更改注入。

1 个答案:

答案 0 :(得分:0)

所以我找到的唯一解决方案是不在Singleton中初始化上下文。但是在我的servlet启动时设置它。

Singleton:

public class AnnotationContextCoreLocator { 
    private AnnotationConfigApplicationContext  context; // Context IOC

    private AnnotationContextCoreLocator() {
        this.context = new AnnotationConfigApplicationContext();
        //this.context.register(ContextCoreMockConfiguration.class);
        //this.context.refresh();
    }

     .....

     }

Servlet init

String configCoreClass = servlet.getInitParameter("contextCoreConfigurationClass");
AnnotationContextCoreLocator.getInstance().register( Class.forName(configCoreClass) );
AnnotationContextCoreLocator.getInstance().refresh();       
AdherentService adherentService = AnnotationContextCoreLocator.getInstance().getBean(AdherentService.class);
...