Spring 3.1.2:未设置ApplicationEventPublisher

问题描述 投票:1回答:2

我有一个这样定义的类:

public class MyClass extends SimpleChannelInboundHandler<DataFrame<ByteBuf>> implements ApplicationEventPublisherAware

(SimpleChannelInboundHandler是一个io.netty类。)

然后,在我的xml文件中,我像这样定义MyClass:

<bean id="MyClass" class="com.mypackage.MyClass" />

根据文件:

在配置时,Spring容器将检测到EmailService实现ApplicationEventPublisherAware并将自动调用setApplicationEventPublisher()。

但是当我运行它时它是空的。

有什么想法吗?

谢谢

java spring applicationcontext
2个回答
1
投票

ApplicationEventPublisherAware的常见用法模式如下:

package example;

import org.springframework.stereotype.*;
import org.springframework.context.*;

@Component
public class MyBean implements ApplicationEventPublisherAware {
  ApplicationEventPublisher applicationEventPublisher;

  public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
    System.out.println("publisher: " + applicationEventPublisher);
    this.applicationEventPublisher = applicationEventPublisher;
  }

  ... (use applicationEventPublisher in methods)
}

您只需要确保通过组件scan / configuration / <bean>标记将bean真正添加到上下文中,尝试将其注入另一个bean来检查它。


0
投票

您应该使用ApplicationContext的getBean方法来获取MyClass的实例,而不是使用new关键字自己初始化。这样Spring Container可以设置ApplicationEventPublisher。

© www.soinside.com 2019 - 2024. All rights reserved.