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

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

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

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

拿bean生命周期中的例子加上这个接口测试
https://blog.csdn.net/csj50/article/details/107975473

1、添加BeanLifeCycle.java

package com.example.base;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Component;

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

	private boolean isRunning = false;

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

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

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

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

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

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

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

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

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

	
	@Override
	public boolean isAutoStartup() {
		System.out.println("========== 执行SmartLifecycle接口isAutoStartup方法");
		return true;
	}

	
	@Override
	public boolean isRunning() {
		System.out.println("========== 执行SmartLifecycle接口isRunning方法");
		return isRunning;
	}

	
	@Override
	public int getPhase() {
		return 0;
	}

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

	
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		if ("threadPool".equals(beanName)) {
			System.out.println("========== 执行postProcessBeforeInitialization方法" + beanName);
		}
		return bean;
	}

	
	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		if ("threadPool".equals(beanName)) {
			System.out.println("========== 执行postProcessAfterInitialization方法" + beanName);
		}
		return bean;
	}

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

}

2、执行结果:

2022-01-28 14:01:30.222 [] INFO  [main] com.example.myboot.MybootApplication :Starting MybootApplication on LAPTOP-M5PHBUE5 with PID 76596 (D:workspacestudymyboottargetclasses started by sjcui in D:workspacestudymyboot)
2022-01-28 14:01:30.229 [] INFO  [main] com.example.myboot.MybootApplication :The following profiles are active: model1,model2,dev
2022-01-28 14:01:31.189 [] DEBUG [main] org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration :Searching for mappers annotated with @Mapper
2022-01-28 14:01:31.190 [] DEBUG [main] org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration :Using auto-configuration base package 'com.example.myboot'
2022-01-28 14:01:31.256 [] INFO  [main] org.springframework.data.repository.config.RepositoryConfigurationDelegate :Multiple Spring Data modules found, entering strict repository configuration mode!
2022-01-28 14:01:31.261 [] INFO  [main] org.springframework.data.repository.config.RepositoryConfigurationDelegate :Bootstrapping Spring Data repositories in DEFAULT mode.
2022-01-28 14:01:31.289 [] INFO  [main] org.springframework.data.repository.config.RepositoryConfigurationDelegate :Finished Spring Data repository scanning in 7ms. Found 0 repository interfaces.
2022-01-28 14:01:31.432 [] DEBUG [main] org.apache.ibatis.logging.LogFactory :Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
2022-01-28 14:01:31.434 [] WARN  [main] org.mybatis.spring.mapper.ClassPathMapperScanner :No MyBatis mapper was found in '[com.example.myboot]' package. Please check your configuration.
2022-01-28 14:01:31.650 [] INFO  [main] c.u.j.configuration.EnableEncryptablePropertiesBeanFactoryPostProcessor :Post-processing PropertySource instances
2022-01-28 14:01:31.651 [] INFO  [main] com.ulisesbocchio.jasyptspringboot.EncryptablePropertySourceConverter :Skipping PropertySource configurationProperties [class org.springframework.boot.context.properties.source.ConfigurationPropertySourcesPropertySource
2022-01-28 14:01:31.652 [] INFO  [main] com.ulisesbocchio.jasyptspringboot.EncryptablePropertySourceConverter :Skipping PropertySource servletConfigInitParams [class org.springframework.core.env.PropertySource$StubPropertySource
2022-01-28 14:01:31.652 [] INFO  [main] com.ulisesbocchio.jasyptspringboot.EncryptablePropertySourceConverter :Skipping PropertySource servletContextInitParams [class org.springframework.core.env.PropertySource$StubPropertySource
2022-01-28 14:01:31.653 [] INFO  [main] com.ulisesbocchio.jasyptspringboot.EncryptablePropertySourceConverter :Converting PropertySource systemProperties [org.springframework.core.env.PropertiesPropertySource] to EncryptableMapPropertySourceWrapper
2022-01-28 14:01:31.653 [] INFO  [main] com.ulisesbocchio.jasyptspringboot.EncryptablePropertySourceConverter :Converting PropertySource systemEnvironment [org.springframework.boot.env.SystemEnvironmentPropertySourceEnvironmentPostProcessor$OriginAwareSystemEnvironmentPropertySource] to EncryptableSystemEnvironmentPropertySourceWrapper
2022-01-28 14:01:31.653 [] INFO  [main] com.ulisesbocchio.jasyptspringboot.EncryptablePropertySourceConverter :Converting PropertySource random [org.springframework.boot.env.RandomValuePropertySource] to EncryptablePropertySourceWrapper
2022-01-28 14:01:31.653 [] INFO  [main] com.ulisesbocchio.jasyptspringboot.EncryptablePropertySourceConverter :Converting PropertySource applicationConfig: [classpath:/config/application-dev.yml] [org.springframework.boot.env.OriginTrackedMapPropertySource] to EncryptableMapPropertySourceWrapper
2022-01-28 14:01:31.653 [] INFO  [main] com.ulisesbocchio.jasyptspringboot.EncryptablePropertySourceConverter :Converting PropertySource applicationConfig: [classpath:/config/application-model2.yml] [org.springframework.boot.env.OriginTrackedMapPropertySource] to EncryptableMapPropertySourceWrapper
2022-01-28 14:01:31.653 [] INFO  [main] com.ulisesbocchio.jasyptspringboot.EncryptablePropertySourceConverter :Converting PropertySource applicationConfig: [classpath:/config/application-model1.yml] [org.springframework.boot.env.OriginTrackedMapPropertySource] to EncryptableMapPropertySourceWrapper
2022-01-28 14:01:31.653 [] INFO  [main] com.ulisesbocchio.jasyptspringboot.EncryptablePropertySourceConverter :Converting PropertySource applicationConfig: [classpath:/config/application.properties] [org.springframework.boot.env.OriginTrackedMapPropertySource] to EncryptableMapPropertySourceWrapper
2022-01-28 14:01:31.653 [] INFO  [main] com.ulisesbocchio.jasyptspringboot.EncryptablePropertySourceConverter :Converting PropertySource applicationConfig: [classpath:/config/application.yml] [org.springframework.boot.env.OriginTrackedMapPropertySource] to EncryptableMapPropertySourceWrapper
========== 执行BeanNameAware接口
========== 执行BeanFactoryAware接口
========== 执行ApplicationContextAware接口
========== 执行@PostConstruct注解
========== 执行InitializingBean接口
2022-01-28 14:01:31.728 [] INFO  [main] o.s.context.support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker :Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$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] com.ulisesbocchio.jasyptspringboot.filter.DefaultLazyPropertyFilter :Property Filter custom Bean not found with name 'encryptablePropertyFilter'. Initializing Default Property Filter
2022-01-28 14:01:31.853 [] INFO  [main] com.ulisesbocchio.jasyptspringboot.resolver.DefaultLazyPropertyResolver :Property Resolver custom Bean not found with name 'encryptablePropertyResolver'. Initializing Default Property Resolver
2022-01-28 14:01:31.855 [] INFO  [main] com.ulisesbocchio.jasyptspringboot.detector.DefaultLazyPropertyDetector :Property Detector custom Bean not found with name 'encryptablePropertyDetector'. Initializing Default Property Detector
2022-01-28 14:01:32.325 [] INFO  [main] org.springframework.boot.web.embedded.tomcat.TomcatWebServer :Tomcat initialized with port(s): 8088 (http)
2022-01-28 14:01:32.461 [] INFO  [main] org.springframework.web.context.ContextLoader :Root WebApplicationContext: initialization completed in 2163 ms
2022-01-28 14:01:32.827 [] INFO  [main] org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor :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] com.ulisesbocchio.jasyptspringboot.encryptor.DefaultLazyEncryptor :String Encryptor custom Bean not found with name 'jasyptStringEncryptor'. Initializing Default String Encryptor
2022-01-28 14:01:32.968 [] INFO  [main] com.ulisesbocchio.jasyptspringboot.configuration.StringEncryptorBuilder :Encryptor config not found for property jasypt.encryptor.key-obtention-iterations, using default value: 1000
2022-01-28 14:01:32.968 [] INFO  [main] com.ulisesbocchio.jasyptspringboot.configuration.StringEncryptorBuilder :Encryptor config not found for property jasypt.encryptor.pool-size, using default value: 1
2022-01-28 14:01:32.968 [] INFO  [main] com.ulisesbocchio.jasyptspringboot.configuration.StringEncryptorBuilder :Encryptor config not found for property jasypt.encryptor.provider-name, using default value: null
2022-01-28 14:01:32.968 [] INFO  [main] com.ulisesbocchio.jasyptspringboot.configuration.StringEncryptorBuilder :Encryptor config not found for property jasypt.encryptor.provider-class-name, using default value: null
2022-01-28 14:01:32.968 [] INFO  [main] com.ulisesbocchio.jasyptspringboot.configuration.StringEncryptorBuilder :Encryptor config not found for property jasypt.encryptor.salt-generator-classname, using default value: org.jasypt.salt.RandomSaltGenerator
2022-01-28 14:01:32.970 [] INFO  [main] com.ulisesbocchio.jasyptspringboot.configuration.StringEncryptorBuilder :Encryptor config not found for property jasypt.encryptor.string-output-type, using default value: base64
2022-01-28 14:01:33.403 [] INFO  [main] com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure :Init DruidDataSource
2022-01-28 14:01:33.586 [] INFO  [main] com.alibaba.druid.pool.DruidDataSource :{dataSource-1} inited
2022-01-28 14:01:33.757 [] DEBUG [main] org.mybatis.spring.SqlSessionFactoryBean :Parsed mapper file: 'file [D:workspacestudymyboottargetclassescomcreatexmlTblTeacherInfMapper.xml]'
2022-01-28 14:01:33.771 [] DEBUG [Druid-ConnectionPool-Create-196340990] druid.sql.Connection :{conn-10001,procId-2} connected
2022-01-28 14:01:33.831 [] INFO  [main] com.example.service.TaskBlackListCreateService :创建黑名单 启动初始化..........
2022-01-28 14:01:34.008 [] INFO  [main] io.lettuce.core.EpollProvider :Starting without optional epoll library
2022-01-28 14:01:34.009 [] INFO  [main] io.lettuce.core.KqueueProvider :Starting without optional kqueue library
2022-01-28 14:01:50.211 [] INFO  [main] com.example.service.TaskHotProductService :定时器启动......
2022-01-28 14:01:50.213 [] INFO  [main] com.example.service.TaskPVoneCacheService :启动定时器 PV一级缓存消费..........
2022-01-28 14:01:50.214 [] INFO  [main] com.example.service.TaskPVTwoCacheService :启动定时器 PV二级缓存消费..........
2022-01-28 14:01:50.216 [] INFO  [main] com.example.service.TaskPrizeCreateService :生成奖品信息 启动初始化..........
2022-01-28 14:01:50.218 [] INFO  [main] com.example.service.TaskQunRandomCreateService :随机展示QQ群 启动初始化..........
2022-01-28 14:01:50.243 [] INFO  [main] com.example.service.TaskRankingCreateService :生成榜单 启动初始化..........
2022-01-28 14:01:50.245 [] INFO  [main] com.example.service.TaskTTPrizeCreateService :天天抽奖 启动初始化..........
2022-01-28 14:01:50.246 [] INFO  [main] com.example.service.TaskWeiBoDayHourService :热度刷新任务 启动初始化..........
2022-01-28 14:01:50.383 [] INFO  [Thread-4] com.example.service.TaskPVTwoCacheService :d出pop=null
2022-01-28 14:01:50.667 [] INFO  [Thread-2] com.example.service.TaskHotProductService :刷新缓存完成
2022-01-28 14:01:51.152 [] INFO  [Thread-2] com.example.service.TaskHotProductService :刷新缓存A完成
2022-01-28 14:01:51.569 [] INFO  [Thread-2] com.example.service.TaskHotProductService :刷新缓存B完成
2022-01-28 14:01:51.569 [] INFO  [Thread-2] com.example.service.TaskHotProductService :product定时刷新完成......
2022-01-28 14:01:52.166 [] INFO  [main] springfox.documentation.spring.web.PropertySourcedRequestMappingHandlerMapping :Mapped URL path [/v2/api-docs] onto method [public org.springframework.http.ResponseEntity springfox.documentation.swagger2.web.Swagger2Controller.getdocumentation(java.lang.String,javax.servlet.http.HttpServletRequest)]
2022-01-28 14:01:52.297 [] INFO  [main] org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor :Initializing ExecutorService 'applicationTaskExecutor'
2022-01-28 14:01:52.417 [] WARN  [main] o.s.b.a.t.ThymeleafAutoConfiguration$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] tk.mybatis.mapper.autoconfigure.MapperCacheDisabler :Clear tk.mybatis.mapper.util.MsUtil CLASS_CACHE cache.
2022-01-28 14:01:52.459 [] INFO  [main] tk.mybatis.mapper.autoconfigure.MapperCacheDisabler :Clear tk.mybatis.mapper.genid.GenIdUtil CACHE cache.
2022-01-28 14:01:52.460 [] INFO  [main] tk.mybatis.mapper.autoconfigure.MapperCacheDisabler :Clear tk.mybatis.mapper.version.VersionUtil CACHE cache.
2022-01-28 14:01:52.460 [] INFO  [main] tk.mybatis.mapper.autoconfigure.MapperCacheDisabler :Clear EntityHelper entityTableMap cache.
2022-01-28 14:01:52.460 [] DEBUG [main] org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration :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] springfox.documentation.spring.web.plugins.documentationPluginsBootstrapper :Context refreshed
2022-01-28 14:01:52.708 [] INFO  [main] springfox.documentation.spring.web.plugins.documentationPluginsBootstrapper :Found 1 custom documentation plugin(s)
2022-01-28 14:01:52.746 [] INFO  [main] springfox.documentation.spring.web.scanners.ApiListingReferenceScanner :Scanning for api listing references
2022-01-28 14:01:52.868 [] INFO  [main] s.documentation.spring.web.readers.operation.CachingOperationNameGenerator :Generating unique operation named: addCartUsingPOST_1
2022-01-28 14:01:52.870 [] INFO  [main] s.documentation.spring.web.readers.operation.CachingOperationNameGenerator :Generating unique operation named: delCartUsingPOST_1
2022-01-28 14:01:52.875 [] INFO  [main] s.documentation.spring.web.readers.operation.CachingOperationNameGenerator :Generating unique operation named: findAllUsingPOST_1
2022-01-28 14:01:52.877 [] INFO  [main] s.documentation.spring.web.readers.operation.CachingOperationNameGenerator :Generating unique operation named: updateCartUsingPOST_1
2022-01-28 14:01:52.971 [] INFO  [main] s.documentation.spring.web.readers.operation.CachingOperationNameGenerator :Generating unique operation named: deleteUsingGET_1
2022-01-28 14:01:52.972 [] INFO  [main] s.documentation.spring.web.readers.operation.CachingOperationNameGenerator :Generating unique operation named: findByIdUsingGET_1
2022-01-28 14:01:52.974 [] INFO  [main] s.documentation.spring.web.readers.operation.CachingOperationNameGenerator :Generating unique operation named: insertUsingGET_1
2022-01-28 14:01:52.975 [] INFO  [main] s.documentation.spring.web.readers.operation.CachingOperationNameGenerator :Generating unique operation named: updateUsingGET_1
2022-01-28 14:01:54.127 [] INFO  [main] org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor :No TaskScheduler/ScheduledExecutorService bean found for scheduled processing
2022-01-28 14:01:54.142 [] INFO  [main] org.springframework.boot.web.embedded.tomcat.TomcatWebServer :Tomcat started on port(s): 8088 (http) with context path ''
2022-01-28 14:01:54.143 [] INFO  [main] com.ulisesbocchio.jasyptspringboot.caching.RefreshScopeRefreshedEventListener :Refreshing cached encryptable property sources on ServletWebServerInitializedEvent
2022-01-28 14:01:54.143 [] INFO  [main] c.u.jasyptspringboot.caching.CachingDelegateEncryptablePropertySource :Property Source systemProperties refreshed
2022-01-28 14:01:54.143 [] INFO  [main] c.u.jasyptspringboot.caching.CachingDelegateEncryptablePropertySource :Property Source systemEnvironment refreshed
2022-01-28 14:01:54.143 [] INFO  [main] c.u.jasyptspringboot.caching.CachingDelegateEncryptablePropertySource :Property Source random refreshed
2022-01-28 14:01:54.143 [] INFO  [main] c.u.jasyptspringboot.caching.CachingDelegateEncryptablePropertySource :Property Source applicationConfig: [classpath:/config/application-dev.yml] refreshed
2022-01-28 14:01:54.144 [] INFO  [main] c.u.jasyptspringboot.caching.CachingDelegateEncryptablePropertySource :Property Source applicationConfig: [classpath:/config/application-model2.yml] refreshed
2022-01-28 14:01:54.144 [] INFO  [main] c.u.jasyptspringboot.caching.CachingDelegateEncryptablePropertySource :Property Source applicationConfig: [classpath:/config/application-model1.yml] refreshed
2022-01-28 14:01:54.144 [] INFO  [main] c.u.jasyptspringboot.caching.CachingDelegateEncryptablePropertySource :Property Source applicationConfig: [classpath:/config/application.properties] refreshed
2022-01-28 14:01:54.144 [] INFO  [main] c.u.jasyptspringboot.caching.CachingDelegateEncryptablePropertySource :Property Source applicationConfig: [classpath:/config/application.yml] refreshed
2022-01-28 14:01:54.144 [] INFO  [main] com.ulisesbocchio.jasyptspringboot.EncryptablePropertySourceConverter :Converting PropertySource server.ports [org.springframework.core.env.MapPropertySource] to EncryptableMapPropertySourceWrapper
2022-01-28 14:01:54.144 [] INFO  [main] com.ulisesbocchio.jasyptspringboot.EncryptablePropertySourceConverter :Skipping PropertySource configurationProperties [class org.springframework.boot.context.properties.source.ConfigurationPropertySourcesPropertySource
2022-01-28 14:01:54.144 [] INFO  [main] com.ulisesbocchio.jasyptspringboot.EncryptablePropertySourceConverter :Skipping PropertySource servletConfigInitParams [class org.springframework.core.env.PropertySource$StubPropertySource
2022-01-28 14:01:54.144 [] INFO  [main] com.ulisesbocchio.jasyptspringboot.EncryptablePropertySourceConverter :Converting PropertySource servletContextInitParams [org.springframework.web.context.support.ServletContextPropertySource] to EncryptableEnumerablePropertySourceWrapper
2022-01-28 14:01:54.145 [] INFO  [main] com.example.myboot.MybootApplication :Started MybootApplication in 24.436 seconds (JVM running for 24.808)
========== 执行CommandLineRunner接口run方法
2022-01-28 14:01:57.433 [] INFO  [Thread-10] com.example.service.TaskWeiBoDayHourService :天刷新完成..........
2022-01-28 14:01:57.575 [] INFO  [Thread-10] com.example.service.TaskWeiBoDayHourService :周刷新完成..........
2022-01-28 14:01:57.751 [] INFO  [Thread-10] com.example.service.TaskWeiBoDayHourService :月刷新完成..........

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

参考资料:
https://blog.csdn.net/lk142500/article/details/90270592

注:最新代码上传至https://github.com/csj50/myboot
 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5719889.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存