我应该如何在不使用autowire的情况下使用xml构造函数arg连接Spring 4.2 ApplicationEventPublisher?
我看到有很多实现,但是如何在不使用autowire和xml配置的情况下使用默认实现?有几个选项,您可以使用注释、实现和接口,或者在xml或java配置中显式声明依赖关系 要获得您可以实现并实现方法的设置,则我应该如何在不使用autowire的情况下使用xml构造函数arg连接Spring 4.2 ApplicationEventPublisher?,spring,events,Spring,Events,我看到有很多实现,但是如何在不使用autowire和xml配置的情况下使用默认实现?有几个选项,您可以使用注释、实现和接口,或者在xml或java配置中显式声明依赖关系 要获得您可以实现并实现方法的设置,则ApplicationContext知道此接口,并将调用setter以向您提供ApplicationEventPublisher public SomeClass implementens ApplicationEventPublisherAware { private Applica
ApplicationContext
知道此接口,并将调用setter以向您提供ApplicationEventPublisher
public SomeClass implementens ApplicationEventPublisherAware {
private ApplicationEventPublisher publisher;
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.publisher= applicationEventPublisher;
}
}
使用注释,您只需将@Autowired
放在字段上即可
public SomeClass implementens ApplicationEventPublisherAware {
@Autowired
private ApplicationEventPublisher publisher;
}
如果它是一个必需的依赖项,我建议使用构造函数注入,额外的好处(IMHO)是您可以使字段成为final
,并且您不能构造无效的实例
public SomeClass implementens ApplicationEventPublisherAware {
private final ApplicationEventPublisher publisher;
@Autowired
public SomeClass(ApplicationEventPublisher applicationEventPublisher) {
this.publisher= applicationEventPublisher;
}
当使用Java配置时,您可以简单地创建一个带注释的方法,该方法将ApplicationEventPublisher
作为参数
@Configuration
public class SomeConfiguration {
@Bean
public SomeClass someClass(ApplicationEventPublisher applicationEventPublisher) {
return new SomeClass(applicationEventPublisher);
}
}
对于需要自动连接构造函数的XML,可以在特定的bean元素上指定
<bean id="someId" class="SomeClass" autowire="constructor" />
像applicationEventMulticaster这样的东西正是我想要的。当我连接到中时,我得到以下结果:无法将类型为[org.springframework.context.event.SimpleApplicationEventMulticaster]的构造函数参数值转换为所需类型[org.springframework.context.ApplicationEventPublisher]:Doh。对不起,我的错,那是行不通的。我删除了答案的这一部分,在Java配置中,这非常简单,如果您自动连接构造函数,它也可以在xml中工作。问题是我使用的是xml配置,无法使用自动连接:(.如果情况变得更糟,我可以只添加接口,但我希望避免这种情况。自动连线的实际实现是什么?我觉得奇怪的是,我不能只引用自动连线放入的同一个bean。谢谢你的帮助。你看过我的上一次编辑吗?为什么你不能自动连线一个s的构造函数ingle bean?如果所有其他方法都失败了,是的,我可以这样做。目标是不必自动连接它,并且能够通过xml上下文配置指定它。我希望避免在需要发布服务器的任何地方都使用该接口。我的目标是只连接发布服务器,尽管构造函数是我的bean。我只是不知道连接什么在那里。