【问题标题】:Add Bean and Interceptor to the context of an application from an external jar从外部 jar 将 Bean 和拦截器添加到应用程序的上下文中
【发布时间】:2016-11-25 16:19:37
【问题描述】:

我有一个具有以下配置类的 Web 应用程序:

@Configuration
@EnableWebMvc
@EnableSpringDataWebSupport
class CustomMvcConfiguration extends WebMvcConfigurerAdapter {

    @Bean
    public MyBean myBean() {
        return new MyBean();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LocaleChangeInterceptor());
    }   
}

我想在应用程序上添加一个 jar 的依赖项,向上下文添加另一个 bean 和另一个拦截器。在另一个项目中,我有另一个 WebMvcConfigurerAdapter 类,但它没有运行:

@Configuration
@EnableWebMvc
@EnableSpringDataWebSupport
class OtherCustomMvcConfiguration extends WebMvcConfigurerAdapter {

    @Bean
    public OtherBean otherBean() {
        return new OtherBean();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CustomInterceptor());
    }   
}

如果我尝试将 OtherBean 注入到应用程序的类中,则 web 上下文中不存在:

@Inject
private OtherBean otherBean;

而且 CustomInterceptor 没有运行。如何从外部模块向应用程序添加 bean 和拦截器?

【问题讨论】:

    标签: java spring spring-mvc servlets


    【解决方案1】:

    我认为您只需要在 MVC 配置中添加正确的 @Include 注释即可。

    @Include(OtherCustomMvcConfiguration.class)    
    class CustomMvcConfiguration extends WebMvcConfigurerAdapter {
    ...
    }
    

    【讨论】:

    • 我不想修改我的 CustomMvcConfiguration,我只想将 bean 添加到上下文中,并在 pom.xml 文件中包含依赖项
    • 然后,您需要在项目的某处添加@ComponentScan 注解并指定OtherCustomMvcConfiguration 类的包/类名
    猜你喜欢
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    • 2018-07-10
    • 2019-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多