- Event
1 @Data 2 public class MyBeanEvent extends ApplicationEvent { 3 private String msg; 4 5 public MyBeanEvent(Object source) { 6 super(source); 7 8 this.msg = (String) source; 9 } 10 }
- Publisher
1 @Component 2 public class MyPublisher { 3 @Inject 4 private ApplicationContext context; 5 6 public void publish(String msg) { 7 context.publishEvent(new MyBeanEvent(msg)); 8 } 9 }
- Listener
1 @Component 2 public class MyListener implements ApplicationListener<MyBeanEvent> { 3 4 @Override 5 public void onApplicationEvent(MyBeanEvent event) { 6 System.out.println("listen: " + event.getMsg()); 7 } 8 }
- Config
1 @Configuration 2 @ComponentScan("idv.steven.info.tse") 3 public class MyEventConfig { 4 5 }
- Main
1 public class MyTestMain { 2 3 public static void main(String[] args) { 4 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyEventConfig.class); 5 MyPublisher publisher = context.getBean(MyPublisher.class); 6 publisher.publish("Hello World"); 7 context.close(); 8 } 9 }
listen: Hello World
沒有留言:
張貼留言