簡體   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);
    }
}

我認為@Bean將放入new AuthorizeInterceptor(); 進入IOC,並在方法addInterceptors()調用authorizelInterceptor()將獲得在IOC中注冊的bean。 如果使用代理,則addInterceptors()調用的方法authorizelInterceptor() addInterceptors()將不進行代理。

@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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM