我应该如何在 Spring 4.2 ApplicationEventPublisher 中连接而不使用使用 xml 构造函数 arg 的自动装配?

tes*_*123 3 events spring

我看到有很多实现,但是如何在不使用自动装配和使用 xml 配置的情况下使用默认实现?

M. *_*num 5

有几个选项,您可以使用注解、实现和接口或在 xml 或 java 配置中显式声明依赖项。

为了得到ApplicationEventPublisher你可以实现ApplicationEventPublisherAware和实现方法,ApplicationContext知道这个接口并将调用setter给你ApplicationEventPublisher

public SomeClass implementens ApplicationEventPublisherAware {
    private ApplicationEventPublisher publisher;

    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher= applicationEventPublisher;
    }
}
Run Code Online (Sandbox Code Playgroud)

有了注释,你就可以放在@Autowired场上

public SomeClass implementens ApplicationEventPublisherAware {
    @Autowired
    private ApplicationEventPublisher publisher;
}
Run Code Online (Sandbox Code Playgroud)

如果它是必需的依赖项,我建议使用构造函数注入,额外的好处(恕我直言)是您可以创建该字段final并且您不能构造无效的实例。

public SomeClass implementens ApplicationEventPublisherAware {
    private final ApplicationEventPublisher publisher;

    @Autowired
    public SomeClass(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher= applicationEventPublisher;
    }
Run Code Online (Sandbox Code Playgroud)

使用 Java Config 时,您可以简单地创建一个带@Bean注释的方法,该方法将一个ApplicationEventPublisher作为参数。

@Configuration
public class SomeConfiguration {

    @Bean
    public SomeClass someClass(ApplicationEventPublisher applicationEventPublisher) {
        return new SomeClass(applicationEventPublisher);
    }
}
Run Code Online (Sandbox Code Playgroud)

对于 XML,您需要自动装配构造函数,您可以在特定的 bean 元素上指定它。

<bean id="someId" class="SomeClass" autowire="constructor" />
Run Code Online (Sandbox Code Playgroud)