IOC初始化执行自定义方法

(1)实现CommandLineRunner接口

我们在开发中可能会有这样的情景。需要在容器启动的时候执行一些内容。比如读取配置文件,数据库连接之类的。SpringBoot给我们提供了两个接口来帮助我们实现这种需求。这两个接口分别为CommandLineRunner和ApplicationRunner。他们的执行时机为容器启动完成的时候。
这两个接口中有一个run方法,我们只需要实现这个方法即可。这两个接口的不同之处在于:ApplicationRunner中run方法的参数为ApplicationArguments,而CommandLineRunner接口中run方法的参数为String数组。下面我写两个简单的例子,来看一下这两个接口的实现。

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)实现ApplicationRunner接口

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注解
如果有多个实现类,而你需要他们按一定顺序执行的话,可以在实现类上加上@Order注解。@Order(value=整数值)。SpringBoot会按照@Order中的value值从小到大依次执行。

(3)初始化方法加上@PostConstruct注解

初始化方法加上@PostConstruct注解,注意该类需要时Bean

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

}

(4)静态代码块

这个Java的基础语法,但是同样适用于Spring

static{
    
    
 XXX
}

(5)通过 @Bean创建自己定义Bean和启动时运行相关程序

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

猜你喜欢

转载自blog.csdn.net/Octopus21/article/details/111083728
今日推荐