SpringApplication know

SpringApplication

SpringApplication Spring Boot drive guide based Spring application context

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
    .........  
}
@ComponentScan is introduced in the beginning of Spring FrameWork3.1 version
@EnableAutoConfiguration: activate automatic assembly @Enable -> @ beginning of Enable (Enable the beginning of a name is called active mode)
  •  @EnableWebMvc
  •  @EnableTransactionManagement
  •  @EnableAspectJAutoProxy
  •  @EnableAsync
@SpringBootConfiguration: equivalent to @Configguration -> Configuration Class notes 

@Component "derivative" of

(read notes Spring programming model: https://github.com/spring-projects/spring-framework/wiki/Spring-Annotation-Programming -model
@Component @Service is the following annotations and other element (meta - annotations-)

@Component -> @ ComponentScan
treatment class -> ConfigurationClassParser

scan type -> ClassPathBeanDefinitionScanner
        ClassPathBeanDefinitionScanner
ClassPathScanningCandidateComponentProvider
    protected void registerDefaultFilters() {
        this.includeFilters.add(new AnnotationTypeFilter(Component.class));
           ........
    }
 

So we scanned all Component annotations, that is, following a few

 
  • @Service

 

@Component
public @interface Service{
    ........
}

 

  • @Controller

 

@Component
public @interface Controller{
    ........
}

 

  • @Repository

 

@Component
public @interface Repository{
    ........
}

 

  • @Configuration

 

@Component
public @interface Configuration{
    ........
}

 Spring mode Notes: Stereotype Annotations (in the Spring marked in any  @Component component can be a candidate scan mode which is annotated)

 

 Spring annotation-driven examples

Annotation driven context AnnotionConfigApplicationContext, Spring FrameWork 3.0 start importing

@Configuration
 public  class SpringAnnotationDemo { 

    public  static  void main (String [] args) {
         // the XML configuration file drive the ClassPathXmlApplicationContext
         // the Annotation drive (both looking for the BeanDefinition) 
        AnnotationConfigApplicationContext context = new new AnnotationConfigApplicationContext ();
         // register a Configuration class SpringAnnotationDemo = 
        context.register (SpringAnnotationDemo. class );
         // context startup 
        context.refresh (); 
        System.out.println (. context.getBean (SpringAnnotationDemo class )); 
    }
}

 

 

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
@SpringBootApplication current mark some of the features 
@SpringBootApplication
@SpringBootConfiguration
@Configuration
@Component
above is equivalent to gradually @SpringBootApplication @Component, further reflects the derivation of the following @Component said, the final destination or Bean
    static void public main (String [] args) { 
        new new SpringApplicationBuilder (Application.class ) 
                .properties ( "the server.port = 0") // 0 means that the operating system be available to the random port                 .run (args); 
    }


Spring Boot exemplary guide

public static void main(String[] args) {
        SpringApplication springApplication = new SpringApplication(Application.class);
        Map<String,Object> proprities = new LinkedHashMap<>();
        proprities.put("server.port","0");
        springApplication.setDefaultProperties(proprities);

   ConfigurableApplicationContext context = springApplication.run(args);
     System.out.println(context.getBean(Application.class));
}

 

 Non-web application example of adjustment

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication springApplication = new SpringApplication(Application.class);
        Map<String,Object> proprities = new LinkedHashMap<>();
        proprities.put("server.port","0");
        springApplication.setDefaultProperties(proprities);
        //设置为非web应用
        springApplication.setWebApplicationType(WebApplicationType.NONE);
        ConfigurableApplicationContext context =springApplication.run (args); 
        System.out.println (. context.getBean (the Application class ));
         // output current Spring ApplicationContext the Boot application class name 
        System.out.println ( "current Spring application context classes: "+ context.getClass () getName ());. 
    } 

}

Output: current context of application Spring classes: org.springframework.context.annotation.AnnotationConfigApplicationContext (this is what we wrote earlier SpringAnnotationDemo inside the context)

 

Configuration SpringBoot source

 

SpringApplication type inference

When not be set up Web type, which uses inferred

-> SpringApplication () -> dedeuceWebApplicationType () first inferred WebApplicationType.SERVLET (Spring boot 2.0.3 version 2.2.1 version deduceEnvironmentClass inferred WebApplicationType.NONE)

 

WebApplicationType.REACTIVE:Spring WebFlux
    DispatcherHandler
    spring-boot-starter-webflux 存在
WebApplicationType.SERVLET:Spring MVV
    Spring-boot-starter-web 存在
WebApplicationType.NONE: Non-type Web 
    Servlet does not exist
    Spring Web context ConfigurableWebApplicationContext there is no
      spring-boot-starter-web does not exist (this place is the pom file of)
      the Spring-the Boot-Starter-webflux does not exist
(according to the presence or absence of the following SpringApplication will be able to know what the environment [environment one that is in version 2.2.1: StandardEnvironment])

Web manual intervention type

Set webApplicationType familiar to WebApplicationType.NONE

 

 

Spring Boot event

public  class SpringEventListenerDemo { 

    public  static  void main (String [] args) { 
        GenericApplicationContext context = new new GenericApplicationContext ();
         // Add Event Listeners
 //         context.addApplicationListener (the ApplicationListener new new <the ApplicationEvent> () {
 //             @Override
 //             public onApplicationEvent void (the ApplicationEvent event) {
 //                 System.err.println ( "listen to events:" event +);
 //             }
 //         }); 

        // add listener custom 
        context.addApplicationListener (new new ClosedListener ()); 

        // start the spring application context 
        context.refresh (); 

        // two events, one ContextRefreshedEvent, one PayloadApplicationEvent
         // the Spring Application Context Published 
        context.publishEvent ( "the HelloWorld"); // release the contents of an event HelloWorld
         // one is my own event 
        context.publishEvent ( new new MyEvent ( "HelloWorld 2019" )); 

        // close the application context 
        context.close (); 
    } 

    Private  static  class ClosedListener the implements ApplicationListener <ContextClosedEvent> { 

        @override 
        public void onApplicationEvent (ContextClosedEvent Event) { 
            System.out.println ( "Close Time Context" + Event); 
        } 
    } 

    Private  static  class the MyEvent the extends the ApplicationEvent { 


        public the MyEvent (Source Object) {
             Super (Source); 
        } 
    } 

}

 

Spring Event

ContextRefreshedEvent
  ApplicationContextEvent
    ApplicationEvent
refresh()->finishRefresh() ->publishEvent(new ContextRefreshedEvent(this))
ContextClosedEvent

  ApplicationContextEvent
    ApplicationEvent
refresh()->finishRefresh() ->publishEvent(new ContextRefreshedEvent(this))


Custom Event

PayloadApplicationEvent

 

Spring events are ApplicationEvent type

 

Spring events sent by ApplicationEventMulticaster # multicastEvent (ApplicationEvent event, @Nullable ResolvableType eventType)

 

Spring type of event ApplicationEvent

 

Spring event listener ApplicationListener

 

Spring event broadcaster ApplicationEventMulticaster

 

Spring Event understood as a message

  ApplicationEvent corresponds to the message content  

  ApplicationListener corresponds to the message to consumers, subscribers

  ApplicationEventMulticaster corresponds to the message producer, publisher

 

Spring Boot event listener example

@EnableAutoConfiguration
 public  class SpringBootEventDemo {
     public  static  void main (String [] args) {
         new new SpringApplicationBuilder (SpringBootEventDemo. Class ) 
                .listeners (Event -> { 
                    System.out.println ( "listen to the event:" + event.getClass (). getName ()); 
                }) // increase listener 
                .run (args); // run 
    } 
}
  1. ApplicationStartingEvent
  2. ApplicationEnvironmentPreparedEvent
  3. ApplicationContextInitializedEvent
  4. ApplicationPreparedEvent
  5. ContextRefreshedEvent
  6. ServletWebServerInitializedEvent
  7. ApplicationStartedEvent
  8. ApplicationReadyEvent
  9. ContextClosedEvent
  10. ApplicationFailedEvent (special circumstances)

SpringBoot event listeners
org.springframework.context.ApplicationListener=\
org.springframework.boot.ClearCachesApplicationListener,\
org.springframework.boot.builder.ParentContextCloserApplicationListener,\
org.springframework.boot.context.FileEncodingApplicationListener,\
org.springframework.boot.context.config.AnsiOutputApplicationListener,\
org.springframework.boot.context.config.ConfigFileApplicationListener,\
org.springframework.boot.context.config.DelegatingApplicationListener,\
org.springframework.boot.context.logging.ClasspathLoggingApplicationListener,\
org.springframework.boot.context.logging.LoggingApplicationListener,\
org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener

ConfigFileApplicationListener listen ApplicationEnvironmentPreparedEvent event so application.properties load file or application.yml

 

Spring boot Many components depend on the Spring Boot event listener implementation, essentially Spring FrameWork event / listener mechanism

 

Conclusion is SpringApplication use

  Spring application context (ApplicationContext) life cycle control annotation-driven Bean

  Spring Event / monitor (ApplicationEventMulticaster) mechanism to load or initialize components

Guess you like

Origin www.cnblogs.com/zhangliang1726/p/11876453.html