在 Spring 中注册 bean 的更好方法

Better way to register beans in Spring

我是 Spring 的新人。我也了解依赖注入和控制反转的过程。但是几天前我发现了一个源代码,这让我不得不思考它。

如果我没记错的话,Beans可以通过Stereotype注解来注册——@Component、@Service等

在我发现的代码中,class 有一些逻辑定义,但没有注释。接下来,相同的 class 将在某些 @Configuration class 中初始化,就像这样:

@Bean
public Foo fooBean() {
   return new Foo();
}

你能告诉我这些选项之间有什么不同以及它们在什么时候使用吗?谢谢指教。

@Configuration 用于定义您的应用程序的配置。最后 @Bean@Service@Component 都会注册一个 bean,但是使用 @Configuration 和在一个地方定义的所有 bean(服务、组件)会使你的应用程序更井井有条,更容易排除故障。

@Configuration@Bean 的最大好处是允许您创建 spring 个未用 @Component 或其任何子项装饰的 bean(@Service@Repository 等等)。当您 want/need 定义在与 Spring 没有直接交互的外部库中定义的 spring beans(可能由您或其他人编写)时,这真的很有帮助。

例如

您有一个由外部提供商创建的 jar,其中包含 class:

public class EmailSender {

    private String config1;
    private String config2;
    //and on...

    public void sendEmail(String from, String to, String title, String body, File[] attachments) {
        /* implementation */
    }
}

由于 class 在外部 jar 中,您无法修改它。不过,Spring 允许您基于此 class 创建 spring beans(记住,bean 是对象,而不是 class)。

在你的项目中,你会有这样的东西:

import thepackage.from.externaljar.EmailSender;

@Configuration
public class EmailSenderConfiguration {

    @Bean
    public EmailSender emailSender() {
        EmailSender emailSender = new EmailSender();
        emailSender.setConfig1(...);
        emailSender.setConfig2(...);
        //and on...
        return emailSender;
    }
}

然后您可以根据需要注入 bean:

@Service
public class MyService {

    @Autowired
    private EmailSender emailSender;
}