我在Spring Boot应用程序中使用自定义过滤器,似乎有2种方法可以注册过滤器。
- >使用@Bean
注册过滤器
@Bean
public Filter AuthenticationFilter() {
return new AuthenticationFilter();
}
- >使用@Component
对过滤器进行旋转
@Component
public class AuthenticationFilter implements Filter {}
我很困惑的是差异是什么以及为什么我应该使用一个而不是另一个?
答案 0 :(得分:5)
这很大程度上取决于个人偏好。
使用@Component
需要启用组件扫描。有些人不喜欢使用组件扫描,因为他们发现很难确定你的豆子来自哪里。使用@Bean
方法声明所有内容可以避免这种情况,但代价是(略微)编写更多Java配置。
使用@Bean
的另一个原因是您可能无法控制过滤器的来源,即您无法使用@Component
对其进行注释,因此使用@Bean
声明它{1}}方法是您唯一的选择。