我想通過定製的jar提供一個默認的bean。只有當用戶實現一個特定的abstract
類時,應該跳過默認的bean注入。如何在條件中提供Spring中的默認bean?
以下設置已正常工作,除了一件事情:default
有線類中的任何注入類都是null
!我可能會錯過什麼?
@Configration
public class AppConfig {
//use the default service if the user does not provide an own implementation
@Bean
@Conditional(MissingServiceBean.class)
public MyService myService() {
return new MyService() {};
}
}
@Component
public abstract class MyService {
@Autowired
private SomeOtherService other;
//default impl of the method, that may be overridden
public void run() {
System.out.println(other); //null! Why?
}
}
public class MissingServiceBean implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return context.getBeanFactory().getBeansOfType(MyService.class).isEmpty();
}
}
MyService
bean已創建並且也可以被注入。但包含的類是空的。
如果我刪除@Conditioanl
註釋,所有內容都按預期工作。
使用XML配置你可以做到這一點,但這不是你想要的方式嗎? – 2014-08-27 08:36:49
對,我想只有基於註釋的配置。 – membersound 2014-08-27 08:38:49