注册过滤器时@Bean和@Component之间的区别?

Mar*_*rco 4 spring spring-boot

我在Spring Boot应用程序中使用自定义过滤器,似乎有2种方法可以注册过滤器.

- >使用@Bean注册过滤器

   @Bean
    public Filter AuthenticationFilter() {
        return new AuthenticationFilter();
    }
Run Code Online (Sandbox Code Playgroud)

- >使用@Component对Filter进行Anotate

@Component
public class AuthenticationFilter implements Filter {}
Run Code Online (Sandbox Code Playgroud)

我很困惑的是,差异是什么以及为什么我应该使用一个而不是另一个?

And*_*son 6

这在很大程度上取决于个人偏好.

使用@Component要求组件扫描启用.有些人不喜欢使用组件扫描,因为他们发现很难确定你的豆子来自哪里.使用@Bean方法声明所有内容可以避免这种情况,但代价是(略微)编写更多Java配置.

使用的另一个原因@Bean是您可能无法控制Filter的源,即您无法对其进行注释,@Component因此使用@Bean方法声明它是您唯一的选择.