Event-driven model (mechanism) Spring in

Description: event-driven model is another form of the Observer pattern, the observer is equivalent to the listener, the viewer is equivalent to the event source

Objective: event source generates an event, the listener listens for events

Summary: event - the event handling model

User registration, when you want to send e-mail and text messages illustrate

Define an event

/ * * 
 * Spring automatically registered in the event to applicationContext 
 * There constructor by passing in the event sources, some scenes may be used, the event source of the present example is UserService 
 * / 
public  class UserRegisterEvent the extends the ApplicationEvent 
{ 
    / * * 
     * 
     * / 
    Private  static Final Long serialVersionUID = 1L ;
     // registered user objects 
    Private UserBean the user; 

    / * * 
     * override the constructor 
     objects * @param source occurrence of the event 
     * @param user registered user object 
     * / 
    public UserRegisterEvent (Object Source, the UserBean User) { 
        Super (Source); 
        the this.user = user;
    }

    public UserBean getUser() {
        return user;
    }
    
    
}

Define event listeners

@Component
public class RegisterListener implements ApplicationListener<UserRegisterEvent>
{
    /**
     * 实现监听
     * @param userRegisterEvent
     */
    @Override
    @Async
    public void onApplicationEvent(UserRegisterEvent userRegisterEvent) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //获取注册用户对象
        UserBean user =userRegisterEvent.getUser ();
         // ../ logic omitted
         // output register user information 
        the System. OUT .println ( " registration information, user name: " + user.getName () + " , Password: " + user.getPassword ( )); 
    } 
}

 

Guess you like

Origin www.cnblogs.com/moris5013/p/11119901.html