简体   繁体   English

如何像Spring一样实现@bean

[英]how to implement @bean like Spring

@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);
    }
}

I think @Bean will put the new AuthorizeInterceptor(); 我认为@Bean将放入new AuthorizeInterceptor(); into IOC and in method addInterceptors() call authorizelInterceptor() will get the bean registered in IOC. 进入IOC,并在方法addInterceptors()调用authorizelInterceptor()将获得在IOC中注册的bean。 if use proxy, method authorizelInterceptor() called in addInterceptors() will not do proxy. 如果使用代理,则addInterceptors()调用的方法authorizelInterceptor() addInterceptors()将不进行代理。

@Bean is a method level annotation which simply provides the bean configuration to the Spring container and the container uses it to inject the respective dependency. @Bean是方法级别的注释,它仅向Spring容器提供Bean配置,并且容器使用它来注入相应的依赖项。 In short,it is just alternative to defining the bean using xml <bean/> tags. 简而言之,它只是使用xml <bean/>标记定义bean的替代方法。

I generally use @Bean while writing the simple unit tests, to provide the bean definitions in the same Test class file (rather than defining a separate xml for bean configurations). 我通常在编写简单的单元测试时使用@Bean,以在同一Test类文件中提供bean定义(而不是为bean配置定义单独的xml)。

I recommend you to go through the below link for more details: 我建议您通过以下链接获取更多详细信息:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM