hpf_huang 2016-11-03 06:41 采纳率: 0%
浏览 1146
已采纳

Spring 事件类Demo,出错了,提示未添加Bean,但我找不到啊

/**

  • 自定义事件 */

public class DemoEvent extends ApplicationEvent{
private static final long serialVerSionUID = 1L;
private String msg;

public DemoEvent(Object source,String msg) {
    super(source);
    this.msg = msg;
}

public String getMsg() {
    return msg;
}

public void setMsg(String msg) {
    this.msg = msg;
}

}

/**

  • 事件监听器 */

@Component
//实现ApplicationListener接口,并指定监听的事件类型
public class DemoListener implements ApplicationListener{

//使用onApplicationEvent方法对消息进行接受处理
public void onApplicationEvent(DemoEvent event) {

    String msg = event.getMsg();

    System.out.println("我(bean-demoListener)接受到了bean-demoPublisger发布的消息:" + msg);
}

}

/**

  • 事件发布类 */

@Component
public class DemoPublisher {
@Autowired
ApplicationContext applicationContext; //注入ApplicationContext用来发布事件

public void publish(String msg) {
    //使用ApplicationContext的publishEvent方法来发布
    applicationContext.publishEvent(new DemoEvent(this,msg)); 
}

}

/**

  • 配置类 */

@Configuration
@Component("com.jiudao.event")
public class EventConfig {

}

/**

  • 运行 */

public class Main {

public static void main(String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EventConfig.class);

    DemoPublisher demoPublisher = context.getBean(DemoPublisher.class);

    demoPublisher.publish("hello application event");

    context.close();
}

}

运行提示:Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.jiudao.event.DemoPublisher] is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:371)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:331)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:972)
at com.jiudao.event.Main.main(Main.java:14)

  • 写回答

1条回答 默认 最新

  • hpf_huang 2016-11-03 08:27
    关注

    好吧,解决了。是配置文件里的@ComponentScan 写成了 @Component

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?