springboot项目创建笔记33 之《初始化资源》

时间:2025-04-27 13:54:46

以前用springmvc时,程序初始化资源用@PostConstruct注解和ApplicationContextAware接口。
springboot提供了一个新接口可以实现这个功能,就是CommandLineRunner接口。比如程序启动后,进行数据库资源的初始化、redis缓存的初始化等。

拿bean生命周期中的例子加上这个接口测试
/csj50/article/details/107975473

1、添加

package ;

import ;
import ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

@Component
public class BeanLifeCycle implements BeanNameAware, BeanFactoryAware, ApplicationContextAware, InitializingBean,
		DisposableBean, SmartLifecycle, BeanPostProcessor, CommandLineRunner {

	private boolean isRunning = false;

	@Override
	public void setBeanName(String name) {
		("========== 执行BeanNameAware接口");
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		("========== 执行BeanFactoryAware接口");
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		("========== 执行ApplicationContextAware接口");
	}

	@PostConstruct
	public void initBean() {
		("========== 执行@PostConstruct注解");
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		("========== 执行InitializingBean接口");
	}

	@PreDestroy
	public void destroyBean() {
		("========== 执行@PreDestroy注解");
	}

	@Override
	public void destroy() throws Exception {
		("========== 执行DisposableBean接口");
	}

	@Override
	public void start() {
		("========== 执行SmartLifecycle接口start方法");
		isRunning = true;
	}

	@Override
	public void stop() {
		("========== 执行SmartLifecycle接口stop方法");
		isRunning = false;
	}

	/**
	 * 返回true时start方法会被自动执行,返回false则不会
	 */
	@Override
	public boolean isAutoStartup() {
		("========== 执行SmartLifecycle接口isAutoStartup方法");
		return true;
	}

	/**
	 * 1. 只有该方法返回false时,start方法才会被执行。<br/>
	 * 2. 只有该方法返回true时,stop(Runnable callback)或stop()方法才会被执行。
	 */
	@Override
	public boolean isRunning() {
		("========== 执行SmartLifecycle接口isRunning方法");
		return isRunning;
	}

	/**
	 * 如果工程中有多个实现接口SmartLifecycle的类,则这些类的start的执行顺序按getPhase方法返回值从小到大执行。<br/>
	 * 例如:1比2先执行,-1比0先执行。 stop方法的执行顺序则相反,getPhase返回值较大类的stop方法先被调用,小的后被调用。
	 */
	@Override
	public int getPhase() {
		return 0;
	}

	@Override
	public void stop(Runnable callback) {
		("========== 执行SmartLifecycle接口stop(Runnable callback)方法");
		();
		isRunning = false;
	}

	/**
	 * 实例化Bean之前
	 */
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		if ("threadPool".equals(beanName)) {
			("========== 执行postProcessBeforeInitialization方法" + beanName);
		}
		return bean;
	}

	/**
	 * 实例化Bean之后
	 */
	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		if ("threadPool".equals(beanName)) {
			("========== 执行postProcessAfterInitialization方法" + beanName);
		}
		return bean;
	}

	@Override
	public void run(String... args) throws Exception {
		("========== 执行CommandLineRunner接口run方法");
	}

}

2、执行结果:

2022-01-28 14:01:30.222 [] INFO  [main]  :Starting MybootApplication on LAPTOP-M5PHBUE5 with PID 76596 (D:\workspace\study\myboot\target\classes started by sjcui in D:\workspace\study\myboot)
2022-01-28 14:01:30.229 [] INFO  [main]  :The following profiles are active: model1,model2,dev
2022-01-28 14:01:31.189 [] DEBUG [main]  :Searching for mappers annotated with @Mapper
2022-01-28 14:01:31.190 [] DEBUG [main]  :Using auto-configuration base package ''
2022-01-28 14:01:31.256 [] INFO  [main]  :Multiple Spring Data modules found, entering strict repository configuration mode!
2022-01-28 14:01:31.261 [] INFO  [main]  :Bootstrapping Spring Data repositories in DEFAULT mode.
2022-01-28 14:01:31.289 [] INFO  [main]  :Finished Spring Data repository scanning in 7ms. Found 0 repository interfaces.
2022-01-28 14:01:31.432 [] DEBUG [main]  :Logging initialized using 'class .slf4j.Slf4jImpl' adapter.
2022-01-28 14:01:31.434 [] WARN  [main]  :No MyBatis mapper was found in '[]' package. Please check your configuration.
2022-01-28 14:01:31.650 [] INFO  [main]  :Post-processing PropertySource instances
2022-01-28 14:01:31.651 [] INFO  [main]  :Skipping PropertySource configurationProperties [class 
2022-01-28 14:01:31.652 [] INFO  [main]  :Skipping PropertySource servletConfigInitParams [class $StubPropertySource
2022-01-28 14:01:31.652 [] INFO  [main]  :Skipping PropertySource servletContextInitParams [class $StubPropertySource
2022-01-28 14:01:31.653 [] INFO  [main]  :Converting PropertySource systemProperties [] to EncryptableMapPropertySourceWrapper
2022-01-28 14:01:31.653 [] INFO  [main]  :Converting PropertySource systemEnvironment [$OriginAwareSystemEnvironmentPropertySource] to EncryptableSystemEnvironmentPropertySourceWrapper
2022-01-28 14:01:31.653 [] INFO  [main]  :Converting PropertySource random [] to EncryptablePropertySourceWrapper
2022-01-28 14:01:31.653 [] INFO  [main]  :Converting PropertySource applicationConfig: [classpath:/config/] [] to EncryptableMapPropertySourceWrapper
2022-01-28 14:01:31.653 [] INFO  [main]  :Converting PropertySource applicationConfig: [classpath:/config/] [] to EncryptableMapPropertySourceWrapper
2022-01-28 14:01:31.653 [] INFO  [main]  :Converting PropertySource applicationConfig: [classpath:/config/] [] to EncryptableMapPropertySourceWrapper
2022-01-28 14:01:31.653 [] INFO  [main]  :Converting PropertySource applicationConfig: [classpath:/config/] [] to EncryptableMapPropertySourceWrapper
2022-01-28 14:01:31.653 [] INFO  [main]  :Converting PropertySource applicationConfig: [classpath:/config/] [] to EncryptableMapPropertySourceWrapper
========== 执行BeanNameAware接口
========== 执行BeanFactoryAware接口
========== 执行ApplicationContextAware接口
========== 执行@PostConstruct注解
========== 执行InitializingBean接口
2022-01-28 14:01:31.728 [] INFO  [main] $BeanPostProcessorChecker :Bean '' of type [$$EnhancerBySpringCGLIB$$920009b9] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2022-01-28 14:01:31.844 [] INFO  [main]  :Property Filter custom Bean not found with name 'encryptablePropertyFilter'. Initializing Default Property Filter
2022-01-28 14:01:31.853 [] INFO  [main]  :Property Resolver custom Bean not found with name 'encryptablePropertyResolver'. Initializing Default Property Resolver
2022-01-28 14:01:31.855 [] INFO  [main]  :Property Detector custom Bean not found with name 'encryptablePropertyDetector'. Initializing Default Property Detector
2022-01-28 14:01:32.325 [] INFO  [main]  :Tomcat initialized with port(s): 8088 (http)
2022-01-28 14:01:32.461 [] INFO  [main]  :Root WebApplicationContext: initialization completed in 2163 ms
2022-01-28 14:01:32.827 [] INFO  [main]  :Initializing ExecutorService
MyListener2 init
app startup at 2022-01-28T14:01:32.929
MyListener1 init
app startup at 2022-01-28T14:01:32.929
MyFilter1 init
MyFilter2 init
2022-01-28 14:01:32.955 [] INFO  [main]  :String Encryptor custom Bean not found with name 'jasyptStringEncryptor'. Initializing Default String Encryptor
2022-01-28 14:01:32.968 [] INFO  [main]  :Encryptor config not found for property -obtention-iterations, using default value: 1000
2022-01-28 14:01:32.968 [] INFO  [main]  :Encryptor config not found for property -size, using default value: 1
2022-01-28 14:01:32.968 [] INFO  [main]  :Encryptor config not found for property -name, using default value: null
2022-01-28 14:01:32.968 [] INFO  [main]  :Encryptor config not found for property -class-name, using default value: null
2022-01-28 14:01:32.968 [] INFO  [main]  :Encryptor config not found for property -generator-classname, using default value: 
2022-01-28 14:01:32.970 [] INFO  [main]  :Encryptor config not found for property -output-type, using default value: base64
2022-01-28 14:01:33.403 [] INFO  [main]  :Init DruidDataSource
2022-01-28 14:01:33.586 [] INFO  [main]  :{dataSource-1} inited
2022-01-28 14:01:33.757 [] DEBUG [main]  :Parsed mapper file: 'file [D:\workspace\study\myboot\target\classes\com\create\xml\]'
2022-01-28 14:01:33.771 [] DEBUG [Druid-ConnectionPool-Create-196340990]  :{conn-10001,procId-2} connected
2022-01-28 14:01:33.831 [] INFO  [main]  :创建黑名单 启动初始化..........
2022-01-28 14:01:34.008 [] INFO  [main]  :Starting without optional epoll library
2022-01-28 14:01:34.009 [] INFO  [main]  :Starting without optional kqueue library
2022-01-28 14:01:50.211 [] INFO  [main]  :定时器启动......
2022-01-28 14:01:50.213 [] INFO  [main]  :启动定时器 PV一级缓存消费..........
2022-01-28 14:01:50.214 [] INFO  [main]  :启动定时器 PV二级缓存消费..........
2022-01-28 14:01:50.216 [] INFO  [main]  :生成奖品信息 启动初始化..........
2022-01-28 14:01:50.218 [] INFO  [main]  :随机展示QQ群 启动初始化..........
2022-01-28 14:01:50.243 [] INFO  [main]  :生成榜单 启动初始化..........
2022-01-28 14:01:50.245 [] INFO  [main]  :天天抽奖 启动初始化..........
2022-01-28 14:01:50.246 [] INFO  [main]  :热度刷新任务 启动初始化..........
2022-01-28 14:01:50.383 [] INFO  [Thread-4]  :弹出pop=null
2022-01-28 14:01:50.667 [] INFO  [Thread-2]  :刷新缓存完成
2022-01-28 14:01:51.152 [] INFO  [Thread-2]  :刷新缓存A完成
2022-01-28 14:01:51.569 [] INFO  [Thread-2]  :刷新缓存B完成
2022-01-28 14:01:51.569 [] INFO  [Thread-2]  :product定时刷新完成......
2022-01-28 14:01:52.166 [] INFO  [main]  :Mapped URL path [/v2/api-docs] onto method [public <> ..(,)]
2022-01-28 14:01:52.297 [] INFO  [main]  :Initializing ExecutorService 'applicationTaskExecutor'
2022-01-28 14:01:52.417 [] WARN  [main] $DefaultTemplateResolverConfiguration :Cannot find template location: classpath:/templates/ (please add some templates or check your Thymeleaf configuration)
2022-01-28 14:01:52.459 [] INFO  [main]  :Clear  CLASS_CACHE cache.
2022-01-28 14:01:52.459 [] INFO  [main]  :Clear  CACHE cache.
2022-01-28 14:01:52.460 [] INFO  [main]  :Clear  CACHE cache.
2022-01-28 14:01:52.460 [] INFO  [main]  :Clear EntityHelper entityTableMap cache.
2022-01-28 14:01:52.460 [] DEBUG [main]  :Not found configuration for registering mapper bean using @MapperScan, MapperFactoryBean and MapperScannerConfigurer.
========== 执行SmartLifecycle接口isAutoStartup方法
========== 执行SmartLifecycle接口isRunning方法
========== 执行SmartLifecycle接口isAutoStartup方法
========== 执行SmartLifecycle接口start方法
2022-01-28 14:01:52.687 [] INFO  [main]  :Context refreshed
2022-01-28 14:01:52.708 [] INFO  [main]  :Found 1 custom documentation plugin(s)
2022-01-28 14:01:52.746 [] INFO  [main]  :Scanning for api listing references
2022-01-28 14:01:52.868 [] INFO  [main]  :Generating unique operation named: addCartUsingPOST_1
2022-01-28 14:01:52.870 [] INFO  [main]  :Generating unique operation named: delCartUsingPOST_1
2022-01-28 14:01:52.875 [] INFO  [main]  :Generating unique operation named: findAllUsingPOST_1
2022-01-28 14:01:52.877 [] INFO  [main]  :Generating unique operation named: updateCartUsingPOST_1
2022-01-28 14:01:52.971 [] INFO  [main]  :Generating unique operation named: deleteUsingGET_1
2022-01-28 14:01:52.972 [] INFO  [main]  :Generating unique operation named: findByIdUsingGET_1
2022-01-28 14:01:52.974 [] INFO  [main]  :Generating unique operation named: insertUsingGET_1
2022-01-28 14:01:52.975 [] INFO  [main]  :Generating unique operation named: updateUsingGET_1
2022-01-28 14:01:54.127 [] INFO  [main]  :No TaskScheduler/ScheduledExecutorService bean found for scheduled processing
2022-01-28 14:01:54.142 [] INFO  [main]  :Tomcat started on port(s): 8088 (http) with context path ''
2022-01-28 14:01:54.143 [] INFO  [main]  :Refreshing cached encryptable property sources on ServletWebServerInitializedEvent
2022-01-28 14:01:54.143 [] INFO  [main]  :Property Source systemProperties refreshed
2022-01-28 14:01:54.143 [] INFO  [main]  :Property Source systemEnvironment refreshed
2022-01-28 14:01:54.143 [] INFO  [main]  :Property Source random refreshed
2022-01-28 14:01:54.143 [] INFO  [main]  :Property Source applicationConfig: [classpath:/config/] refreshed
2022-01-28 14:01:54.144 [] INFO  [main]  :Property Source applicationConfig: [classpath:/config/] refreshed
2022-01-28 14:01:54.144 [] INFO  [main]  :Property Source applicationConfig: [classpath:/config/] refreshed
2022-01-28 14:01:54.144 [] INFO  [main]  :Property Source applicationConfig: [classpath:/config/] refreshed
2022-01-28 14:01:54.144 [] INFO  [main]  :Property Source applicationConfig: [classpath:/config/] refreshed
2022-01-28 14:01:54.144 [] INFO  [main]  :Converting PropertySource  [] to EncryptableMapPropertySourceWrapper
2022-01-28 14:01:54.144 [] INFO  [main]  :Skipping PropertySource configurationProperties [class 
2022-01-28 14:01:54.144 [] INFO  [main]  :Skipping PropertySource servletConfigInitParams [class $StubPropertySource
2022-01-28 14:01:54.144 [] INFO  [main]  :Converting PropertySource servletContextInitParams [] to EncryptableEnumerablePropertySourceWrapper
2022-01-28 14:01:54.145 [] INFO  [main]  :Started MybootApplication in 24.436 seconds (JVM running for 24.808)
========== 执行CommandLineRunner接口run方法
2022-01-28 14:01:57.433 [] INFO  [Thread-10]  :天刷新完成..........
2022-01-28 14:01:57.575 [] INFO  [Thread-10]  :周刷新完成..........
2022-01-28 14:01:57.751 [] INFO  [Thread-10]  :月刷新完成..........

可以看到CommandLineRunner接口run方法是在bean实例化和初始化之后执行的

参考资料:
/lk142500/article/details/90270592

注:最新代码上传至/csj50/myboot