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)

查看全部
hpf_huang
hpf_huang
2016/11/03 06:41
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复