相同的依赖在旧的Spring MVC应用程序,在那里你会指定application.xml
并声明你的应用程序的豆子,这样春天DI可以实例他们和它们连接在一起,你可能有这样的事情:接线多豆,通过Spring引导@Configuration
<bean id="chargeFactory" class="com.example.myapp.ChargeFactory" />
<bean id="paymentService" class="com.example.myapp.DefaultPaymentService">
<ref id="chargeFactory"/>
</bean>
<bean id="chargeAuditor" class="com.example.myapp.ChargeAuditor">
<ref id="chargeFactory"/>
</bean>
这可能有助于线了下面的代码:
public interface PaymentService {
public void makePayment(Payment payment);
}
public class DefaultPaymentService implements PaymentService {
@Autowired
private ChargeFactory chargeFactory;
@Override
public void makePayment(Payment payment, String key) {
Charge charge = chargeFactory.createCharge(key);
charge.doCharge(payment);
}
}
public class ChargeAuditor {
@Autowired
private ChargeFactory chargeFactory;
public void auditAllCharges(String key) {
List<Charge> charges = chargeFactory.getAllCharges(key);
// blah whatever
}
}
你如何做到在春季启动与@Configuration
类相同豆布线?例如:
@Configuration
public class MyAppInjector {
@Bean
public ChargeFactory chargeFactory() {
return new ChargeFactory();
}
@Bean
public PaymentService paymentService() {
return new DefaultPaymentService(chargeFactory());
}
@Bean
public ChargeAuditor chargeAuditor() {
return new ChargeAuditor(chargeFactory());
}
}
这威力工作,但介绍了一些问题:
- 这将迫使我不得不写我的所有类值构造,这违背一切我从字面上看每教程/文章我遇到过。另外,如果我必须这样做,那么就没有真正的价值
@Autowired
反正... - 在这一点上,我基本上是做“DIY DI”,这是确定的,除了我试图故意使用Spring DI :-)
- 我每次打电话
chargeFactory()
我得到一个新的(原型样式)ChargeFactory
实例。也许我想要一个单身人士。使用这种方法,我必须手动推出我自己的单例实现。
当然,我可以做到这一切,但我觉得我公然滥用/误解如何@Configuration
应该使用,因为它好像我介绍了一大堆的DIY /自行开发的代码来解决Spring DI应该能够为我做的事情。
我该如何参考chargeFactory
bean,并将它连接到paymentService
和chargeAuditor
beans的“提供者方法”中?再次,寻找基于Java的@Configuration
解决方案,而不是编写XML文档来定义配线。
我发现this article这似乎是通过@Configuration
(这导致我相信可能有其他/更好的方法......)接线Spring Boot应用程序中的唯一教程/文档(令人惊讶),但它没有解决:
- 如何指定单VS bean原型实例化模式
- 如果存在豆类的多个实例,我怎么指定实例被连入其中的依赖?
- 如何避免为我的类定义全部的值构造函数,并让Spring/
@Autowired
自动注入字段?
嗯@谢谢@pvpkiran(+1)这是在任何地方记录?如果我**要**'chargerFactory'的原型怎么办?如果我有两个不同的'chargerFactory'实例,我想将它们连接成不同的依赖关系? – smeeb
您可以将@Scope与Bean注释一起使用。我认为这个文档非常清晰http://docs.spring.io/spring-framework/docs/4.0.4.RELEASE/javadoc-api/org/springframework/context/annotation/Bean.html – pvpkiran
嗯,我认为它的在2017年疯狂的人们必须通过Spring Javadocs去寻找**主要功能**的工作方式,但也许这只是我。感谢你! – smeeb