注册过滤器时@Bean和@Component的区别?
Posted
技术标签:
【中文标题】注册过滤器时@Bean和@Component的区别?【英文标题】:Difference between @Bean and @Component when registering a filter? 【发布时间】:2015-05-22 15:14:06 【问题描述】:我在我的 Spring Boot 应用程序中使用自定义过滤器,似乎有两种方法可以注册过滤器。
--> 使用@Bean 注册过滤器
@Bean
public Filter AuthenticationFilter()
return new AuthenticationFilter();
--> 使用@Component 注释过滤器
@Component
public class AuthenticationFilter implements Filter
我很困惑有什么区别以及为什么我应该使用一个而不是另一个?
【问题讨论】:
【参考方案1】:这很大程度上取决于个人喜好。
使用@Component
需要启用组件扫描。有些人不喜欢使用组件扫描,因为他们发现很难确定 bean 的来源。使用@Bean
方法声明所有内容可以避免这种情况,但代价是编写(稍微)更多的 Java 配置。
使用@Bean
的另一个原因是您可能无法控制过滤器的源,即您无法使用@Component
对其进行注释,因此使用@Bean
方法声明它是您唯一的选择。
【讨论】:
但如果我是正确的,那对于 springboot 来说不是 100 有效。 (我真的不明白你对“来自”的意思对于春季启动来说,要走的路就是使用组件并使用 Autowired 获取依赖项。但也许你的观点是另一个,我没有明白:)以上是关于注册过滤器时@Bean和@Component的区别?的主要内容,如果未能解决你的问题,请参考以下文章