IOC initialization and execution of custom methods

(1) Implement the CommandLineRunner interface

We may have such a situation in development. Some content needs to be executed when the container starts. For example, read configuration files, database connections, and the like. SpringBoot provides us with two interfaces to help us achieve this demand. These two interfaces are CommandLineRunner and ApplicationRunner. Their execution timing is when the container is started.
There is a run method in these two interfaces, we only need to implement this method. The difference between the two interfaces is that the parameter of the run method in ApplicationRunner is ApplicationArguments, while the parameter of the run method in the CommandLineRunner interface is an array of String. Below I write two simple examples to take a look at the implementation of these two interfaces.

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;


@Component
public class TestImplCommandLineRunner implements CommandLineRunner {
    
    


    @Override
    public void run(String... args) throws Exception {
    
    

        System.out.println("<<<<<<<<<<<<这个是测试CommandLineRunn接口>>>>>>>>>>>>>>");
    }
}

(2) Implement ApplicationRunner interface

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;


@Component
public class TestImplApplicationRunner implements ApplicationRunner {
    
    


    @Override
    public void run(ApplicationArguments args) throws Exception {
    
    
        System.out.println(args);
        System.out.println("这个是测试ApplicationRunner接口");
    }
}

@Order annotation
If there are multiple implementation classes and you need them to be executed in a certain order, you can add @Order annotations to the implementation class. @Order(value=integer value). SpringBoot will execute from small to large according to the value in @Order.

(3) Add @PostConstruct annotation to the initialization method

The initialization method is annotated with @PostConstruct, pay attention to the Bean when the class needs it

import javax.annotation.PostConstruct;
 
import org.springframework.stereotype.Component;
 
 
@Component
public class MyTest{
    
    
	@PostConstruct
	public void test() throws Exception {
    
    
	 System.out.println("PostConstruct");
	}

}

(4) Static code block

The basic grammar of Java, but the same applies to Spring

static{
    
    
 XXX
}

(5) Create your own defined Bean through @Bean and run related programs at startup

 @Bean
  public XXXX beanName() {
    
    
       //自定义Bean属性
      return XXXX;
  }

Guess you like

Origin blog.csdn.net/Octopus21/article/details/111083728