[JAVA] Event processing is performed in Spring.

What is Spring's "event"?

Spring Framework can generate "events" in the middle of the service. By using this, the processing can be made "loosely coupled", so the processing of the service can be divided into pieces.

Since it works just by sandwiching it between services, it seems to be effective for log output and cache trends. Since it has an independent configuration, it is effective when you want to prevent the processing of the service from becoming long, or when you want someone else to create some of the functions.

This time, instead of implementing the annotations implemented from Spring 4.3, we will make it by implementing the interface and gorigori.

Flow until the event is issued.

  1. Create your own event
  2. Create an event listener
  3. Implement the service
  4. Register event listeners and services in DI
  5. Start the service with Servlet!

1. Create an event.

First, create an event class that inherits ** ApplicationEvent **. ** MyBeanEvent () ** in this is executed.

MyBeanEvent.java


public class MyBeanEvent extends ApplicationEvent {

	public MyBeanEvent(Object source) {
		super(source);
		//TODO auto-generated constructor stub
		System.out.println("Create MyBeanEvent");
	}

}

2. Create an event listener

Then create an event listener Just implement an interface called ** ApplicationListner **.

MyBeanEventListener.java


public class MyBeanEventListener implements ApplicationListener<MyBeanEvent> {

	@Override
	public void onApplicationEvent(MyBeanEvent event) {
		//TODO auto-generated method stub
		System.out.println("Event Has Finished!!");
	}

}

This event listener is always called after the event ends. It might be good to write an end log

3. Create a service.

Then create a ** service ** that runs the event. (I will omit the place to register the bean in DI!)

MyBeanEventService.java



public class MyBeanEventService implements ApplicationEventPublisherAware{

	@Autowired
	private MyBeanEve beanEve;
	private ApplicationEventPublisher publisher;
	
	@Override
	public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
		//TODO auto-generated method stub
		this.publisher = applicationEventPublisher;
		System.out.println("publisher set!!");
		
	}
	
	public void doService(String message) {
		System.out.println("Service Started!");
		beanEve.addMessage(message);
		publisher.publishEvent(new MyBeanEvent(this));
	}

}

Here, the processing that actually works is the doService part. By ** setApplicationEventListenerPublisher ** Will publish an event. publisher is a convenience class that publishes events. You are now executing event processing.

4. Register event listeners and services in DI

Finally, register the event listener and service in the Java config. The Spring Framework is now ready to publish the event. (* ^-^ *)

MyBeanEveConfig.java


@Configuration
@ComponentScan(basePackages = "com.TsugaruInfo.bean")
public class MyBeanEveConfig {
	
	@Bean
	MyBeanEve myBean2() {
		return new MyBeanEve();
	}
	
	@Bean
	public MySampleApplicationListener addListener() {
		return new MySampleApplicationListener();
	}
	
	@Bean
	public MyBeanEventListener mybeanListener() {
		return new MyBeanEventListener();
	}
	
	@Bean
	public MyBeanEventService mybeanService() {
		return new MyBeanEventService();
	}
}

5. Start the service with Servlet!

Finally, run the service on the Servlet or controller. This time it is executed by Servlet. It may not work because I changed it a little (/ _;)

MySampleServlet.java


@WebServlet("/sample")
public class MySampleServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	ApplicationContext app;
		
	@Autowired
	private MyBeanEventService myService;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public void init() throws ServletException{
        super.init();
        SpringBeanAutowiringSupport
        	.processInjectionBasedOnCurrentContext(this);
    }
    
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String message = request.getParameter("message");
		myService.doService(message);
		response.sendRedirect("sample");
	}

Run

Let's embed this Servlet and start the server.

image.png

You should see the characters ** publisher set !! ** printed on the console. (Leave other characters It's proof that the service is properly registered in DI.

Let's access it for a moment and move the method.

image.png

From the characters on the console ** Service → Event → Event Listener ** You can see that it works in the order of.

Summary

If you use it well, you can do the processing you want to use before the service, which is a convenient function. However, for that purpose, the design of what process to divide is very important. ~~ It is better to let the team know the relationship between the service and the event (ry ~~

Think about your design and do smart Spring programming!

Reference book Spring Framework 5 Introduction to programming https://www.amazon.co.jp/Spring-Framework-%E3%83%97%E3%83%AD%E3%82%B0%E3%83%A9%E3%83%9F%E3%83%B3%E3%82%B0%E5%85%A5%E9%96%80-%E6%8E%8C%E7%94%B0-%E6%B4%A5%E8%80%B6%E4%B9%83/dp/4798053740

Recommended Posts

Event processing is performed in Spring.
What is @Autowired in Spring boot?
Spring Autowired is written in the constructor
Asynchronous processing with regular execution in Spring Boot
@Import target is treated as @Configuration in spring
Inject Logger in Spring
What is Spring Tools 4
Use Interceptor in Spring
Microservices in Spring Cloud
Use MouseListener in Processing
When Spring Batch is executed continuously in Oracle, ORA-08177
Get cookies in Spring
Set context-param in Spring Boot
Write Processing in IntelliJ IDEA
Spring with Kotorin --6 Asynchronous processing
Spring Boot 2 multi-project in Gradle
[Swift] What is asynchronous processing?
Measured parallel processing in Java
Error in Spring database connection
Mazume judgment processing in fishing
Major changes in Spring Boot 1.5
NoHttpResponseException in Spring Boot + WireMock
Loop step in Spring Batch
Simultaneous key press in Processing
RSocket is supported in Spring Boot 2.2, so give it a try
ProxyFactory is convenient when you want to test AOP in Spring!
[Spring Boot] Until @Autowired is run in the test class [JUnit5]