Spring expands knowledge: post processors and event listeners

Spring extension

when using ssm. Will find spring first, why?

It should be because we need to hand over the object to srping for unified management,

Let's review first, the two major characteristics of spring

ioc We have worked with spring to help us create classes and decouple our classes

aop You can add some enhanced methods without changing the source code of the class, which can be pre-, post-, exceptions, etc.

When we want to use the framework to achieve more and more functions, we often need to add a lot of bean components. When using it, we can directly use the classes in the ioc container.

post processor

Creating classes is also different

  • Singleton with factory creation
  • with bean creation

These all require corresponding post-processors. Next, let's take a look at the flexible processors that spring provides us. As long as the bean s injected into the container are about to be initialized, the post-processors will be executed. After it is completed, it is put into the spring pool.

bean handler

BeanPostProcessor: The role of the Bean's post-processor is to add our own logic before and after the initialization method is displayed after the Bean object is instantiated and dependency injected. Note that it is triggered after the Bean is instantiated and after the dependency injection is completed. The source code of the interface is as follows

There are two methods in the source code:

postProcessBeforeInitialization: instantiation, dependency injection is completed, and then call display initialization to complete the task of custom initialization of the game

postProcessAfterInitialization: instantiation, dependency injection, execution after initialization

Here we write a small demo to experience

Create a new class called myBeanPostProcessor, we implement the interface of this post processor

Parameter explanation:

Parameter 1 bean: is the object we injected into the ioc

Parameter 2 beanName : is the name of the object we injected into the ioc

public class MyBeanPostProcessor implements BeanPostProcessor {
  public Object postProcessBeforeInitialization(Object bean, String beanName)
      throws BeansException {
    System.out.println(beanName+"Before initialization");
    return bean;
  }

  public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    System.out.println(beanName+"After initialization");
    return bean;
  }
}
copy

Simple example, after implementation, you can see the output information before and after initialization of the injected object

Bean Factory Post Processor

This bean factory processor is some modification to the bean before the creation of all beans. What can we do to the bean before constructing the object,

postProcessBeanFactory method: The parameter has the object of the bean factory, you can view some information

He just returns a created factory object before bena is created, we can view the bean information to be created in the factory

BeanDefinitionRegistryPostProcessor (post bean component information processor)

In order to deal with some configurations when we put the container into spring, such as whether it is a singleton, initialization method, destruction method, etc. post-processor for information

method

The configuration information registration of the postProcessBeanDefinitionRegistrybean object

Enter the bean factory after postProcessBeanFactory

public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry)
      throws BeansException {
    System.out.println("postProcessBeanDefinitionRegistry:" + beanDefinitionRegistry);
  }

  public void postProcessBeanFactory(
      ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
    System.out.println("ConfigurableListableBeanFactory:" + configurableListableBeanFactory);
  }
copy

The various life cycles of Bean components

  • bean component information processor: component information registration
  • The bean factory is created, and the post-factory processor we wrote ourselves is the same,
  • bean creation and injection completed
  • Before initialization
  • loading finished
  • after initial
  • destroy

Small demo, use bean factory to operate bean injection

New configuration file: beanFactoryProcessor.xml, just put two bean objects without any configuration

    <bean id="mypostProcessBeanFactory" class="com.hyc.Processor.MypostProcessBeanFactory"/>
    <bean id="demobean" class="com.hyc.springBean.demoBean"></bean>
copy

Manipulate bean objects with beanFactory, implement configuration, and attribute injection

public class MypostProcessBeanFactory implements BeanFactoryPostProcessor {
  public void postProcessBeanFactory(
      ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
    System.out.println("configurableListableBeanFactory" + configurableListableBeanFactory);
    // get object
    AbstractBeanDefinition demobean =
        (AbstractBeanDefinition) configurableListableBeanFactory.getBeanDefinition("demobean");
    // Set the initialization method
    demobean.setInitMethodName("init1");
    // inject name value
    MutablePropertyValues propertyValues = demobean.getPropertyValues();
    propertyValues.add("name", "PostProcessorFactory bane name");
    // set destroy method
    demobean.setDestroyMethodName("destroy1");
  }
}
copy

Then output the viewing information

Next we duplicate a custom bean factory

Add a bean to the configuration file

    <bean id="mypostProcessBeanFactory2" class="com.hyc.Processor.MypostProcessBeanFactory2"/>
copy

Implement the priority interface for the two factories, set the priority,

Factory No. 1 has a priority of 5

Factory 2 has a priority of 10

public class MypostProcessBeanFactory2 implements BeanFactoryPostProcessor, Ordered {
 //The code of the previous factory is omitted

  public int getOrder() {
    return 10;
  }
copy

start test

It can be seen that the level 5 is executed online

Perfect, the above is the actual combat of using post processors to manipulate bean properties

spring event listener

We can monitor the time that happens in our spring, and we can also customize a spring event listener

We learn this mainly to know what events are dispatched when spring is executed in the container

Here we implement ApplicationListener<ApplicationEvent>

The object in the generic here is the global message, we can also write our own custom

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

  String username;
  String emial;

  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public String getEmial() {
    return emial;
  }

  public void setEmial(String emial) {
    this.emial = emial;
  }

  public MyApplicationEvent(Object source, String username, String emial) {
    super(source);
    this.username = username;
    this.emial = emial;
  }
}
copy

Then create a new configuration file Listener.xml to add the event listener to the spring container

  <bean id="listener" class="com.hyc.listener.myApplicationListener"></bean>
copy

Modify the event listener, let's see what events are dispatched when the bean is generated

public class myApplicationListener implements ApplicationListener<ApplicationEvent> {
  public void onApplicationEvent(ApplicationEvent event) {
    System.out.println("received event" + event);
      //The judgment here is that if there is our own definition content, the event listener will be forced into our custom listener to ensure that our own custom events can also be output.
    if (event instanceof MyApplicationEvent) {
      MyApplicationEvent myApplicationEvent = (MyApplicationEvent) event;
      System.out.println("username" + myApplicationEvent.getUsername());
      System.out.println("User mailbox" + myApplicationEvent.getEmial());
    }
  }
}
copy

test after

public class listenerMain {
  public static void main(String[] args) {
    ClassPathXmlApplicationContext ApplicationContext =
        new ClassPathXmlApplicationContext("Listener.xml");
    //Create event object
    MyApplicationEvent event = new MyApplicationEvent("event content", "james", "123@qq,com");
    //send event
    ApplicationContext.publishEvent(event);
    ApplicationContext.close();
    //
  }
}
copy

It can be seen that the loading process of spring in the figure is becoming more and more obvious.

Tags: Spring Cyber Security Container

Posted by dynodins on Thu, 29 Sep 2022 16:43:12 +0930