如何在启动弹簧时选择性加载bean

Min*_*ang 2 java spring spring-mvc

我的问题是如何在Web应用程序的开头实现选择性加载spring bean.

背景我们的应用程序基于J2EE和Spring.我们在不同的托管服务器上运行相同的Web应用程序 在其中一些托管服务器上,我们只运行Web服务,但在其他服务器上,我们还需要运行报告,调度程序等服务.所有这些服务都在spring配置xml文件中配置为spring bean.所以我们想在启动带有Web服务的服务器时禁用一些未使用的bean.

存在的问题,我试图重写的方法customizeContextorg.springframework.web.context.ContextLoaderListener,从上下文中删除那些未使用的豆子.(我知道这不是一个好主意,删除加载的bean而不是阻止它们在第一个位置加载.那是因为我无法弄清楚如何实现它)但是,我得到了java.lang.IllegalStateException: BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext.

经过一些调查,我得到的BeanFactory不能在这里使用,但我有点卡住,不知道如何实现这个功能.有人可以帮我解决这个问题吗?要么在开始时停止将bean加载到Spring中,要么在Spring启动时从bean中移除bean对我有用.

以下是我重写Method的代码customizeContext.

@Override
protected void customizeContext(ServletContext servletContext, ConfigurableWebApplicationContext applicationContext) {

    super.customizeContext(servletContext, applicationContext);

    ConfigurableListableBeanFactory configurableListableBeanFactory = applicationContext.getBeanFactory();
    BeanDefinitionRegistry beanDefinitionRegistry = (BeanDefinitionRegistry) configurableListableBeanFactory;
    beanDefinitionRegistry.removeBeanDefinition("testBean");
}
Run Code Online (Sandbox Code Playgroud)

Ser*_*sta 5

不要试图加载所有豆子后配置BeanFactory中,你应该有团体豆,只加载与实际运行的服务.

遗留方法是让中间XML文件包含其他文件的导入,这些文件包含我在上面调用的bean 组中的内容,并在主XML文件中导入正确的文件.Spring参考手册中的摘录:依赖于系统环境变量和包含$ {placeholder}标记的XML语句的组合,这些标记根据环境变量的值解析为正确的配置文件路径

但现在选择的工具应该是配置文件.您将bean放在与您的服务相对应的不同配置文件中

@Bean
@Profile("production")
public DataSource productionDataSource() throws Exception {
Run Code Online (Sandbox Code Playgroud)

或者用XML

<beans profile="production">
    <jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/datasource"/>
</beans>
Run Code Online (Sandbox Code Playgroud)

您只需要启用相关的配置文件,可以是programmaticaly:

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.getEnvironment().setActiveProfiles("dev");
Run Code Online (Sandbox Code Playgroud)

甚至作为JVM属性:

-Dspring.profiles.active="profile1,profile2"
Run Code Online (Sandbox Code Playgroud)

参考:Spring参考手册中的环境抽象一章.