如何像Spring一样实现@bean


@Configuration
public class WebAppConfig extends WebMvcConfigurerAdapter {
    @Bean
    AuthorizeInterceptor authorizelInterceptor() {
        return new AuthorizeInterceptor();
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
         registry.addInterceptor(authorizelInterceptor()).addPathPatterns("/user/**");
         super.addInterceptors(registry);
    }
}

我认为@Bean将把new AuthorizeInterceptor();放入IOC, addInterceptors()调用authorizelInterceptor()将使bean在IOC中注册。如果使用代理,在addInterceptors()中调用的authorizelInterceptor()方法将不做代理。

@Bean是一个方法级注释,它简单地向Spring容器提供bean配置,容器使用它来注入相应的依赖项。简而言之,它只是使用xml <bean/>标记定义bean的替代方法。

我通常在编写简单单元测试时使用@Bean,以便在相同的Test类文件中提供bean定义(而不是为bean配置定义单独的xml)。

我建议你通过下面的链接了解更多细节:

http://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch02s02.html

最新更新