注册过滤器时@Bean 和@Component 的区别?
Difference between @Bean and @Component when registering a filter?
我在 Spring 引导应用程序中使用自定义过滤器,似乎有两种方法可以注册过滤器。
--> Register the filter using the @Bean
@Bean
public Filter AuthenticationFilter() {
return new AuthenticationFilter();
}
--> Anotate the Filter using @Component
@Component
public class AuthenticationFilter implements Filter {}
我对它们之间的区别以及为什么我应该使用一个而不是另一个感到困惑?
很大程度上取决于个人喜好。
使用@Component
需要启用组件扫描。有些人不喜欢使用组件扫描,因为他们发现很难确定您的 bean 来自何处。使用 @Bean
方法声明所有内容可以避免这种情况,但代价是编写(稍微)更多 Java 配置。
使用 @Bean
的另一个原因是您可能无法控制过滤器的源,即您不能使用 @Component
对其进行注释,因此使用 @Bean
声明它方法是您唯一的选择。
我在 Spring 引导应用程序中使用自定义过滤器,似乎有两种方法可以注册过滤器。
--> Register the filter using the @Bean
@Bean
public Filter AuthenticationFilter() {
return new AuthenticationFilter();
}
--> Anotate the Filter using @Component
@Component
public class AuthenticationFilter implements Filter {}
我对它们之间的区别以及为什么我应该使用一个而不是另一个感到困惑?
很大程度上取决于个人喜好。
使用@Component
需要启用组件扫描。有些人不喜欢使用组件扫描,因为他们发现很难确定您的 bean 来自何处。使用 @Bean
方法声明所有内容可以避免这种情况,但代价是编写(稍微)更多 Java 配置。
使用 @Bean
的另一个原因是您可能无法控制过滤器的源,即您不能使用 @Component
对其进行注释,因此使用 @Bean
声明它方法是您唯一的选择。