我是春天的新人。我也理解依赖注入和控制反转的过程。但是几天前我发现了一个强制我思考它的源代码。
如果我没错,可以通过Stereotype注释注册Beans - @Component,@ Service等。
在我发现的代码中,将使用一些逻辑定义类,但没有注释。接下来,相同的类将在某些@Configuration类中初始化,如下所示:
@Bean
public Foo fooBean() {
return new Foo();
}
你能告诉我这些选项和使用时有什么不同吗?谢谢你的建议。
答案 0 :(得分:5)
@Configuration
和@Bean
的最大好处是允许您创建未使用@Component
或其任何子项(@Service
,{{ 1}}和那些)。当您需要/需要定义在外部库中定义的Spring bean时,这非常有用,该外部库与Spring没有直接交互(可能由您或其他人编写)。
E.g。
您有一个由包含此类的外部提供程序创建的jar:
@Repository
由于该类位于外部jar中,因此无法对其进行修改。尽管如此,Spring允许您基于此类创建spring bean(请记住,bean是对象,而不是类)。
在您的项目中,您将拥有以下内容:
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 */
}
}
然后你可以根据需要注入bean:
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;
}
}
答案 1 :(得分:0)
@Configuration
用于定义应用程序的配置。最后@Bean
,@Service
,@Component
都将注册一个bean,但使用@Configuration
将所有bean(服务,组件)定义在一个地方会使您的应用更多有条理,更容易排除故障。