0%

spring | @EventListener

事件监听注解。

目录结构如下

1
2
3
4
5
- src.main.java
- com.lou.springboot
- Application.java
- Component1.java
- UserEvent.java

Application.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.lou.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import java.io.IOException;

/**
* Hello shiyanlou!
*/
@SpringBootApplication
public class Application {

public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, IOException {
ConfigurableApplicationContext configurableApplicationContext = SpringApplication.run(Application.class, args);

configurableApplicationContext.publishEvent(new UserEvent(configurableApplicationContext)); // 发送事件

}
}

UserEvent.java

1
2
3
4
5
6
7
8
9
package com.lou.springboot;

import org.springframework.context.ApplicationEvent;

public class UserEvent extends ApplicationEvent {
public UserEvent(Object source) {
super(source);
}
}

Component1.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.lou.springboot;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class Component1 {

private static final Logger logger = LoggerFactory.getLogger(Component.class);

@EventListener // 监听注解
public void aaa(UserEvent event) {
logger.info("123 {}", event);
}
}
请我喝杯咖啡吧~