我何时使用@Bean而不是@Component?

rob*_*lco 3 spring dependency-injection

我对春天的一些事感到困惑.

首先,我什么时候想在一个显式的@Configuration类上使用@Component和一个@Bean来实现@Component?

我可以考虑使用@Component的唯一原因是在@Configuration类中保存自己创建的@Bean方法.还有其他原因吗?

也就是说,如果我使用@Configuration类,我似乎可以手动编写这些bean的接线.IOW,我在@Component上使用@Inject我现在可以在@Bean构造函数中显式指定依赖项(当我在bean方法中创建它时).那么我什么时候想使用@Inject?我觉得我要在这里挖一个兔子洞.

是否有任何好的教程或博客涵盖了做出这些决定的最佳实践或规则?

谢谢

hol*_*s83 8

一个例子:

@Component
public class SomeComponent { }
Run Code Online (Sandbox Code Playgroud)

以上将在实践中创建如下:

public class SomeComponent { }
@Configuration
public class SomeComponentConfig {
    @Bean
    public SomeComponent someComponent() {
        return new SomeComponent();
    }
}
Run Code Online (Sandbox Code Playgroud)

优点@Component很明显:代码更少!

另一方面,@Bean功能强大,有很多用例; 例如,如果SomeComponent在您无法编辑的现有库中,或者您只是不想使用Spring或@Inject注释使其混乱.