我不认为这是一个spring-amqp
特定的问题,但它提供了一个相对整洁的例子来激发我的问题。考虑一下@Configuration
,来自spring-rabbit
Hello World 项目:
@Configuration
public class HelloWorldConfiguration {
…
@Bean /* <-- Optional?! What's the point? */
public ConnectionFactory connectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory("localhost");
return connectionFactory;
}
@Bean
public AmqpAdmin amqpAdmin() {
return new RabbitAdmin(connectionFactory());
}
@Bean
public RabbitTemplate rabbitTemplate() {
RabbitTemplate template = new RabbitTemplate(connectionFactory());
…
}
@Bean
// Every queue is bound to the default direct exchange
public Queue helloWorldQueue() {...}
}
我可以很容易地理解为什么这个AmqpAdmin
函数会产生一个 bean,因此这个Queue
对象看起来是完全合理的。不过,在我看来,这rabbitTemplate
可能connectionFactory
是常规的非 bean 函数。即使是静态函数,非常简单的动物。
为这些功能添加了什么@Bean
注释?它促进了哪些依赖注入模式?
像下面这样的答案无处不在。这些假设我知道我想要一个 bean,并处理为什么我没有得到它。我的问题是不同的:为什么我需要这些东西才能成为 bean?未修饰的功能不是等效的吗?