> Java > java지도 시간 > 본문

봄 주석 이벤트 이벤트

高洛峰
풀어 주다: 2016-11-22 15:37:02
원래의
1509명이 탐색했습니다.

기본 지원

우선 어떤 기본 이벤트가 지원되는지 살펴보자

봄 주석 이벤트 이벤트

프로그램 1(서비스)

우선 살펴보기 프로그램에서

ApplicationEventPublisher는 봄 항목이며 전송을 위해 주입되어야 합니다. ApplicationEventPublisherAware가 구현되어 있기 때문에 setApplicationEventPublisher 메소드가 자동으로 이를 호출하고 브로드캐스트 발신자를 가져옵니다

/**
 * @author Carl
 * @date 2016/8/28
 * @modify 版权所有.(c)2008-2016.广州市森锐电子科技有限公司
 */public class EmailService implements ApplicationEventPublisherAware {    private List<String> blackList;    private ApplicationEventPublisher publisher;    public void setBlackList(List<String> blackList) {        this.blackList = blackList;
    }    public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {        this.publisher = publisher;
    }    /**
     * 具体广播类
     * @param address
     * @param text
     */
    public void sendEmail(String address, String text) {        if (blackList.contains(address)) {
            BlackListEvent event = new BlackListEvent(this, address, text);
            publisher.publishEvent(event);            return;
        }        // send email...
    }
}
로그인 후 복사

프로그램 2(이벤트)

여기에서도 ApplicationEvent를 상속해야 하며, 방송을 수신할 때 얻을 수 있도록 필요한 매개변수 등을 직접 구현할 수 있습니다. 또한 소스

/**
 * @author Carl
 * @date 2016/8/28
 * @modify 版权所有.(c)2008-2016.广州市森锐电子科技有限公司
 */public class BlackListEvent extends ApplicationEvent {  
  private String address;    
private String test;    
public BlackListEvent(Object source, String address, String test) {    
    super(source);        this.address = address;        this.test = test;
    }    public String getAddress() {        return address;
    }    public void setAddress(String address) {        this.address = address;
    }    public String getTest() {        return test;
    }    public void setTest(String test) {        this.test = test;
    }
}
로그인 후 복사

프로그램 3(수신기)

스프링을 사용할 때 여전히 해당 사양 세트를 따라야 합니다. 그런 다음 수신기는 ApplicationListener 인터페이스를 구현해야 합니다. 일반 브로드캐스트를 수신하면 onApplicationEvent 인터페이스가 전달됩니다

물론 spring은 매우 사려 깊고 반드시 ApplicationListener 클래스를 구현하지는 않습니다. 주석 @EventListener

/**
 * @author Carl
 * @date 2016/8/28
 * @modify 版权所有.(c)2008-2016.广州市森锐电子科技有限公司
 */public class BlackListNotifier implements ApplicationListener<BlackListEvent> {  
  private String notificationAddress;    
  public void setNotificationAddress(String notificationAddress) {    
      this.notificationAddress = notificationAddress;
    }    @EventListener
    public void onApplicationEvent(BlackListEvent event) {        // notify appropriate parties via notificationAddress...
        System.out.println("onApplicationEvent, some thing I receive:" + event.getAddress() + ",text:" + event.getTest());
    }    @EventListener(condition = "#event.test == &#39;foo&#39;")    public void onApplicationCustomerEvent(BlackListEvent event) {
        System.out.println("onApplicationCustomerEvent,some thing I receive:" + event.getAddress() + ",text:" + event.getTest());      
        // notify appropriate parties via notificationAddress...
    }    @EventListener({ContextStartedEvent.class, ContextRefreshedEvent.class})    public void handleContextStart() {
        System.out.println("-------------handleContextStart");

    }    /**
     * 参数可以给BlackListEvent 可以不给
     */
    @EventListener(classes = {BlackListEvent.class})    public void handleBlackListEvent() {
        System.out.println("-------------handleBlackListEvent");
    }
}
로그인 후 복사

@EventListener

<를 추가합니다. 🎜> 이 주석을 사용하는 방법을 분석해 보겠습니다. 위 프로그램과 마찬가지로 인터페이스 구현 외에도

조건을 통해 SpEL 표현식을 사용할 수 있습니다. , 조건이 충족되었을 때만 실행됩니다.

이벤트 객체가 트리거될 때 이 클래스가 실행됩니다.

프로그램 4(config bean)

여기서는 주로

/**
 * 配置
 * @author Carl
 * @date 2016/8/28
 * @modify 版权所有.(c)2008-2016.广州市森锐电子科技有限公司
 */@Configurationpublic class AppConfig {    @Bean
    public EmailService emailService() {
        EmailService s = new EmailService();
        List<String> emails = new ArrayList<>(3);
        emails.add("known.spammer@example.org");
        emails.add("known.hacker@example.org");
        emails.add("john.doe@example.org");
        s.setBlackList(emails);        return s;
    }    @Bean
    public BlackListNotifier notifier() {
        BlackListNotifier notifier = new BlackListNotifier();
        notifier.setNotificationAddress("blacklist@example.org");        return notifier;
    }
}
로그인 후 복사


을 수락하기 위해 일부 서비스를 등록하고 브로드캐스트 Bean을 수락합니다.

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!