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

标签 spring events

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

最佳答案

有多种选择,您可以使用注释、实现和接口(interface)或在 xml 或 java 配置中显式声明依赖项。

获取ApplicationEventPublisher您可以实现 ApplicationEventPublisherAware并实现该方法,ApplicationContext 了解此接口(interface),并将调用 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;
}

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

public SomeClass implementens ApplicationEventPublisherAware {
    private final ApplicationEventPublisher publisher;

    @Autowired
    public SomeClass(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher= applicationEventPublisher;
    }

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

@Configuration
public class SomeConfiguration {

    @Bean
    public SomeClass someClass(ApplicationEventPublisher applicationEventPublisher) {
        return new SomeClass(applicationEventPublisher);
    }
}

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

<bean id="someId" class="SomeClass" autowire="constructor" />

关于spring - 我应该如何在 Spring 4.2 ApplicationEventPublisher 中连接而不使用使用 xml 构造函数 arg 的自动连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30419147/

相关文章:

spring - 为什么我们在 Spring Java Configuration 中有 *Adapter 类,而它们不是一般意义上的 Adapter

javascript - 在javascript中使用http请求下载文件

java - NoSuchBeanDefinitionException - 未定义名为 blPU 的 bean - 无法注入(inject) EntityManager JPA

java - 必须只接受特定数值的 validator

java - Spring 中的日志消息银行

html - 使用单个 CSS 事件更改两个元素的属性

forms - 这是在 Google Analytics 中跟踪 AJAX 表单提交的正确代码吗?

Android 异步任务取消/停止

events - 如何捕获 dijit.form.NumberSpinner 的递增和递减事件?

javascript - 在 Javascript 中转发事件