gpt4 book ai didi

java - 如何像Spring一样实现@bean

转载 作者:行者123 更新时间:2023-12-01 09:18:39 28 4
gpt4 key购买 nike

@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()将不会做代理。

最佳答案

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

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

我建议您通过以下链接了解更多详细信息:

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

关于java - 如何像Spring一样实现@bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40327986/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com