event,listener是observer模式一種體現,在spring 3.0.5中,已經能夠使用annotation實現event和eventListner裏。
咱們以spring-webflow裏的hotel booking爲例,看一下實現,步驟以下:
1,創建event
css
public class BookingCreatedEvent extends ApplicationEvent { private static final long serialVersionUID = 3039313222160544111L; private Booking booking; public BookingCreatedEvent(Object source) { super(source); } public BookingCreatedEvent(Object source, Booking booking) { super(source); this.booking = booking; } public Booking getBooking() { return booking; } }
event須要繼承ApplicationEvent。java
2,創建listener
web
@Component public class BookingEventsListener implements ApplicationListener<BookingCreatedEvent> { private static final Logger log = Logger.getLogger(); //listener實現 public void onApplicationEvent(BookingCreatedEvent event) { log.debug("bookingId:" + event.getBooking().getId()); //do something } }
listener須要實現ApplicationListener。
注意在spring 3.0.5中的ApplicationListener是帶泛型的,這樣BookingEventsListener只會監聽BookingCreatedEvent事件。
另外能夠用@Component來註冊組件,這樣就不須要在spring的配置文件中指定了。spring
3,觸發event
數據庫
@Service("bookingService") @Repository public class JpaBookingService implements BookingService, ApplicationContextAware { private ApplicationContext context; public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { log.debug("Autowired applicationContext"); this.context = applicationContext; } //省略的代碼 @Transactional public void persistBooking(Booking booking) throws HibernateException, SQLException { em.persist(booking); log.debug("fire BookingCreatedEvent"); BookingCreatedEvent bookingCreatedEvent = new BookingCreatedEvent(this, booking); //觸發event this.context.publishEvent(bookingCreatedEvent); } }
觸發要實現ApplicationContextAware,用於引入ApplicationContext,因爲bookingService也 是spring組件,因此在系統啓動的時候,ApplicationContext已經注入。也能夠用以下方式直接注入 ApplicationContext。app
@Autowired private ApplicationContext applicationContext;
那麼event listener這種模式的好處是什麼呢?舉個例子,若是客人booking了hotel之後,系統要發email給客人,那咱們就能夠在listener的do something處加入發送email的代碼。
上面咱們講起用@Component把listener註冊成了spring的組件,這樣listener的用途是在runtime的時候解耦。
而若是咱們把listener用配置文件的方式註冊的話,主要的用途是在部署時解耦。
在實際應用中,兩種狀況都有。異步
另外要注意的一點是,service和listener是同步的,在service中的persistBooking有註冊 @Transactional的狀況下,listener中的do something和service中的persistBooking是在同一個tansaction下。
若是要作異步,須要經過MQ或者數據庫中轉。this