如何避免使用依赖项重复初始化BeanPostProcessor

时间:2017-09-13 04:12:51

标签: java spring spring-mvc spring-boot

我遇到了BeanPostProcessor初始化不止一次的问题。它之所以这样做是因为它包含在ApplicationContextConfig中,当ServletContextConfig扫描代码时,它会初始化BeanPostProcessor的另一个独立版本。

这是一个问题的原因是因为每个应用程序应该只有一个BeanPostProcessor(这是因为如果我有多个,则会导致线程问题)。

我无法从BeanPostProcessor的组件扫描中排除ServletContextConfig的原因是因为有一个类依赖于BeanPostProcessor来创建bean。

有什么想法吗?如果可能,我想将ConfigBeanPostProcessor中创建的WebApplicationContextServletContextConfig“分享”。

WebApplicationInitializer.java

public class WebApplicationInitializer extends AbstractServletInitializer 
{
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    @Override
    protected Class<?>[] getApplicationContextConfigClasses() {
        return new Class<?>[]{ApplicationContextConfig.class};
    }

    @Override
    protected Class<?>[] getServletContextConfigClasses() {
        return new Class<?>[]{ServletContextConfig.class};
    }

    @Override
    protected Filter[] getFilters() {
        return new Filter[]{
                new DelegatingFilterProxy(LoggingFilter.FILTER_NAME),
                new DelegatingFilterProxy(MonitoringFilter.FILTER_NAME)
        };
    }
}

ApplicationContextConfig.java

@Configuration
@ComponentScan(basePackageClasses = Application.class, excludeFilters = @Filter({Controller.class, Configuration.class}))
public class ApplicationContextConfig {
    @Bean
    public ConfigBeanPostProcessor() {
        //return ConfigBeanPostProcessor
    }
}

ServletContextConfig.java

@Configuration
@ComponentScan(basePackageClasses = Application.class, includeFilters =             
@ComponentScan.Filter({Controller.class}))
public class ServletContextConfig extends WebMvcConfigurationSupport
{
    @Autowire
    private ClassThatDependsOnConfigPostProcessor class;
}

0 个答案:

没有答案