Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.

About Spring’s source-related features

1 introduction ApplicationContext

ApplicationContext is a core Spring interface that allows the container to create, retrieve, and manage beans from the ApplicationContext.

public interface ApplicationContext extends EnvironmentCapable.ListableBeanFactory.HierarchicalBeanFactory.MessageSource.ApplicationEventPublisher.ResourcePatternResolver {

	/**
	 * Return the unique id of this application context.
	 * @return the unique id of the context, or {@code null} if none
	 */
	@Nullable
	String getId(a);

	/**
	 * Return a name for the deployed application that this context belongs to.
	 * @return a name for the deployed application, or the empty String by default
	 */
	String getApplicationName(a);

	/**
	 * Return a friendly name for this context.
	 * @return a display name for this context (never {@code null})
	 */
	String getDisplayName(a);

	/**
	 * Return the timestamp when this context was first loaded.
	 * @return the timestamp (ms) when this context was first loaded
	 */
	long getStartupDate(a);

	/**
	 * Return the parent context, or {@code null} if there is no parent
	 * and this is the root of the context hierarchy.
	 * @return the parent context, or {@code null} if there is no parent
	 */
	@Nullable
	ApplicationContext getParent(a);

	AutowireCapableBeanFactory getAutowireCapableBeanFactory(a) throws IllegalStateException;

}
Copy the code

ApplicationContext provides the following functions:

  • Access the Bean factory methods of the application component. From the org. Springframework. Beans. Factory. ListableBeanFactory inherited.
public interface ListableBeanFactory extends BeanFactory {... }Copy the code
  • The ability to load file resources in a generic manner. From the org. Springframework. Core. IO. Support. ResourcePatternResolver inherited.
package org.springframework.core.io.support;

import java.io.IOException;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

public interface ResourcePatternResolver extends ResourceLoader {
    String CLASSPATH_ALL_URL_PREFIX = "classpath*:";

    Resource[] getResources(String var1) throws IOException;
}
Copy the code
  • The ability to publish events to registered listeners. From the org. Springframework. Context. ApplicationEventPublisher inherited.
@FunctionalInterface
public interface ApplicationEventPublisher {
	default void publishEvent(ApplicationEvent event) {
		publishEvent((Object) event);
	}
	void publishEvent(Object event);

}
Copy the code
  • The ability to parse messages, supporting internationalization. From the org. Springframework. Context. MessageSource inherited.
public interface MessageSource {

	@Nullable
	String getMessage(String code, @Nullable Object[] args, @Nullable String defaultMessage, Locale locale);

	String getMessage(String code, @Nullable Object[] args, Locale locale) throws NoSuchMessageException;

	String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException;

}
Copy the code
  • Inherited from the parent context, definitions in the descendant context always take precedence. A single parent context can be used by the entire Web application, while each servlet has its own subcontext independent of any other servlet.

2 Description of ApplicationListener

1 ApplicationListener profile

The ApplicationContext event mechanism is the observer design pattern within the design pattern and implements event handling through the ApplicationEvent class and ApplicationListener interface.

When there is an ApplicationListener object in the container, the ApplicationListener object is automatically triggered when the ApplicationContext issues the ApplicationEvent and needs to be controlled by the program. There are also events built into Spring.

Built-in event instructions
ContextRefreshedEvent This event is published when the ApplicationContext is initialized or refreshed. This can also be used in ConfigurableApplicationContext interface refresh () method to happen. Initialization here means that all beans are successfully loaded, the post-processing beans are detected and activated, all Singleton beans are pre-instantiated, and the ApplicationContext container is ready for use
ContextStartedEvent ConfigurableApplicationContext (ApplicationContext interface) start () method in the interface of ApplicationContext starts, the incident was released. You can investigate your database, or you can restart any stopped applications after receiving this event
ContextStoppedEvent ConfigurableApplicationContext interface the stop () when they stop ApplicationContext release this event. You can do the necessary cleaning up after receiving the event
ContextClosedEvent ConfigurableApplicationContext close () method in the interface of closed ApplicationContext, the incident was released. A closed context reaches the end of its life cycle; It cannot be refreshed or restarted
RequestHandledEvent Are Web-specific events that tell all beans that the HTTP request has been processed by the service. This parameter is applicable only to Web applications that use DispatcherServlet. When Spring is used as the front-end MVC controller, the system automatically fires this event when Spring finishes processing the user request

2 ApplicationListener case

1 Prepare a SpringBoot environment

2 Create a custom listener

@Component
public class DemoApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        System.out.println(event);
        System.out.println("TestApplicationListener............................"); }}Copy the code

As you can see, ContextRefreshedEvent has built-in events that are published when ApplicationContext is initialized or refreshed, i.e. listeners can receive callback messages.

3 Start the project and view logs

3 aboutApplicationContextinstructions

1 introduction applicationcontext

From the above knowable ApplicationContext has the ability to publish event from ApplicationEventPublisher interface inheritance. In Spring, you need to inherit the ApplicationEvent class or the ApplicationContextEvent abstract class. The abstract class has only one constructor and takes an Object parameter as the event source. The event source cannot be NULL. So we need to execute super(Object) in our constructor.

public class EventObject implements java.io.Serializable {

    private static final long serialVersionUID = 5516075349620653480L;

    /** * The object on which the Event initially occurred. */
    protected transient Object  source;

    /**
     * Constructs a prototypical Event.
     *
     * @param    source    The object on which the Event initially occurred.
     * @exception  IllegalArgumentException  if source is null.
     */
    public EventObject(Object source) {
        if (source == null)
            throw new IllegalArgumentException("null source");

        this.source = source; }... }Copy the code

Case 2 applicationcontext

1 Prepare a SpringBoot environment

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);

        testEvent();
    }

// @Bean
// public FeignInterceptor feignInterceptor(){
// return new FeignInterceptor();
/ /}

    // Test the event
    public static void testEvent(a) {
        ApplicationContext context = new AnnotationConfigApplicationContext(EventConfig.class);
        DemoEvent demoEvent = new DemoEvent(context, "Xiao Ming".20); context.publishEvent(demoEvent); }}Copy the code

2 Create a custom listener

@Component
public class Demo2ApplicationListener implements ApplicationListener<ApplicationEvent> {
    @Override
    public void onApplicationEvent(ApplicationEvent event) {

        // Handle custom events
        if (event instanceof DemoEvent) {
            System.out.println(event);
            DemoEvent demoEvent = (DemoEvent) event;
            System.out.println("Name:" + demoEvent.getUsername() + ", age: + demoEvent.getAge());

            System.out.println("Custom DemoEvent events..."); }}}Copy the code

3 Create a custom event

public class DemoEvent extends ApplicationEvent {

    private String username;
    private int age;
    
    /**
     * Create a new ApplicationEvent.
     *
     * @param source the object on which the event initially occurred (never {@code null})
     */
    public DemoEvent(Object source, String username, int age) {
        super(source);
        this.username = username;
        this.age = age;
    }


    public String getUsername(a) {
        return username;
    }

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

    public int getAge(a) {
        return age;
    }

    public void setAge(int age) {
        this.age = age; }}Copy the code

4 Start the project and view logs