spring中的aop:Spring中事件处理的小窍门技巧

Spring中提供些Aware相关接口BeanFactoryAware、 ApplicationContextAware、ResourceLoaderAware、ServletContextAware等等其中最常用到是ApplicationContextAware实现ApplicationContextAwareBean在Bean被将会被注入 ApplicationContext例子ApplicationContextAware提供了publishEvent思路方法实现Observer(观察者)设计模式事件传播机提供了针对Bean事件传播功能通过Application.publishEvent思路方法我们可以将事件通知系统内所有ApplicationListener

  Spring事件处理般过程:

  ·定义Event类继承org.springframework.context.ApplicationEvent.

  ·编写发布事件类Publisher实现org.springframework.context.ApplicationContextAware接口.

  ·覆盖思路方法ApplicationContext(ApplicationContext applicationContext)和发布思路方法publish(Object obj)

  ·定义时间监听类EventListener实现ApplicationListener接口实现思路方法onApplicationEvent(ApplicationEvent event).

  java 代码

import org.springframework.context.ApplicationEvent;

/**
* 定义事件信息
* @author
*
*/
public MessageEvent extends ApplicationEvent {

 private String message;

 public void Message(String message){
  this.message = message;
 }

 public String getMessage{
   message;
 }

 public MessageEvent(Object source, String message) {
  super(source);
  this.message = message;
  // TODO Auto-generated constructor stub
 }

 private final long serialVersionUID = 1L;


  java 代码

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.FileXmlApplicationContext;

public Publisher implements ApplicationContextAware {

 private ApplicationContext context;

 @Override
 public void ApplicationContext(ApplicationContext arg0)
 throws BeansException {
  // TODO Auto-generated method stub
  this.context = arg0;
 }

 public void publish(String message){
  context.publishEvent( MessageEvent(this,message));
 }

 public void (String args) {
  ApplicationContext ctx = FileXmlApplicationContext("src/applicationContext.xml");
  Publisher pub = (Publisher) ctx.getBean("publisher");
  pub.publish("Hello World!");
  pub.publish("The quick brown fox jumped over the lazy dog");
 }


  java 代码

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;

public MessageEventListener implements ApplicationListener {

 @Override
 public void _disibledevent=>   .out.prln("Received: " + msEvent.getMessage);
  }
 }


  在运行期ApplicationContext会自动在当前所有Bean中寻找ApplicationListener接口实现并将其作为事件接收对象当Application.publishEvent思路方法所有ApplicationListener接口实现都会被激发每个ApplicationListener可根据事件类型判断是否是自己需要处理事件如上面ActionListener只处理ActionEvent事件

Tags:  spring事件 spring中的事务管理 spring中的事务 spring中的aop

延伸阅读

最新评论

发表评论