Spring项目,项目启动执行方法且执行一次。
在实习过程中,有时候会遇到一些项目启动初始化的需求,比如,将一些数据存入到redis中,又或者通过java流去读取某个文件。
这时候,我们就需要考虑如何实现在项目一启动就去执行某个方法来执行操作。
- 方案一
通过使用@PostConstruct注解
通过测试,该注解可以实现该功能
@Component
public class SystemInit {@PostConstructpublic void init() {System.out.println("=========初始化环境==============");}
}
项目启动之后
进入到源码看看:
package javax.annotation;import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;/*** The PostConstruct annotation is used on a method that needs to be executed* after dependency injection is done to perform any initialization. This* method MUST be invoked before the class is put into service. This* annotation MUST be supported on all classes that support dependency* injection. The method annotated with PostConstruct MUST be invoked even* if the class does not request any resources to be injected. Only one* method can be annotated with this annotation. The method on which the* PostConstruct annotation is applied MUST fulfill all of the following* criteria:* <p>* <ul>* <li>The method MUST NOT have any parameters except in the case of* interceptors in which case it takes an InvocationContext object as* defined by the Interceptors specification.</li>* <li>The method defined on an interceptor class MUST HAVE one of the* following signatures:* <p>* void <METHOD>(InvocationContext)* <p>* Object <METHOD>(InvocationContext) throws Exception* <p>* <i>Note: A PostConstruct interceptor method must not throw application* exceptions, but it may be declared to throw checked exceptions including* the java.lang.Exception if the same interceptor method interposes on* business or timeout methods in addition to lifecycle events. If a* PostConstruct interceptor method returns a value, it is ignored by* the container.</i>* </li>* <li>The method defined on a non-interceptor class MUST HAVE the* following signature:* <p>* void <METHOD>()* </li>* <li>The method on which PostConstruct is applied MAY be public, protected,* package private or private.</li>* <li>The method MUST NOT be static except for the application client.</li>* <li>The method MAY be final.</li>* <li>If the method throws an unchecked exception the class MUST NOT be put into* service except in the case of EJBs where the EJB can handle exceptions and* even recover from them.</li></ul>* @since Common Annotations 1.0* @see javax.annotation.PreDestroy* @see javax.annotation.Resource*/
@Documented
@Retention (RUNTIME)
@Target(METHOD)
public @interface PostConstruct {}
翻译之后,我们可以得知:@PostConstruct注解用于需要在依赖注入完成后执行任何初始化的方法。
- 方案二:
通过实现ApplicationListener< ContextRefreshedEvent >接口,然后是实现onApplicationEvent()方法执行一下操作可以实现。
@Service
public class SvnUserServiceImpl implements SvnUserService, ApplicationListener<ContextRefreshedEvent> {private final Logger logger = LoggerFactory.getLogger(SvnUserServiceImpl.class);@Value("${svn.passwd-httpd.path}")private String passwdHttpd;@Autowiredprivate SvnUserMapper svnUserMapper;@Overridepublic void onApplicationEvent(ContextRefreshedEvent event) {// 保证只执行一次if (event.getApplicationContext().getParent() == null) {this.querySvnUserInfoInit();}}
}
个人还是喜欢第一种方案,原因嘛,各位也是显而易见。。。。
Spring项目,项目启动执行方法且执行一次。相关推荐
- java如何保证一个方法只能执行一次
我们经常会遇到一些情况需要某一个方法或者操作只执行一次,比如说配置信息加载,如果配置信息需要动态刷新,这个不在适用范围.下面列举几种方式 第一种 如果是web容器,可以使用servlet或者Liste ...
- Spring Boot 之异步执行方法
给方法加上 @Async 注解 package me.deweixu.aysncdemo.service; public interface AsyncService {void asyncMetho ...
- oracle一条sql的执行过程,请问执行一条sql的整个过程是怎样的,谢谢!
select count(*) into c from yaoyao_pbj where object_id=7559; select count(*) into c from yaoyao_pbj ...
- spring定时任务需要在项目启动时执行一次
spring定时任务需要在项目启动时执行一次,然后再按照指定规则执行 在定时任务方法上加注解@PostConstruct,不是spring提供的注解,是JAVA原生注解,在初始化servlet之前执行 ...
- springmvc项目在启动完成之后执行一次方法_SpringMVC运行原理
springMVC主要有四大控件,其中有DispatcherServlet,hadlerMapping,HanlerAdapter,ModelAndView. springMVC的运行步骤大致是当客服 ...
- Springboot项目启动后立即执行方法
Springboot项目启动后执行方法,有三种实现方式. 此篇博客介绍的方法可以在程序启动时加载一些自定义的监听器之类的,例如Socket服务的监听器,此时如果使用@PostConstract,Soc ...
- spring项目一启动就自动运行方法(资源加载初始化)
参考一个写的不错的博客,原文请看: https://www.cnblogs.com/baixianlong/p/11117665.html 记录几种常用的方式 1.实现ApplicationRunne ...
- scheduled每天下午1点执行一次_在Spring Boot项目中使用@Scheduled注解实现定时任务...
在java开发中定时任务的实现有多种方式,jdk有自己的定时任务实现方式,很多框架也有定时任务的实现方式.这里,我介绍一种很简单的实现方式,在Spring Boot项目中使用两个注解即可实现. 在sp ...
- 你知道Spring Boot项目是怎么启动的吗?
点击上方蓝色"方志朋",选择"设为星标" 回复"666"获取独家整理的学习资料! 概 述 在Java后端开发领域,大名鼎鼎的Spring B ...
最新文章
- 哈哈哈哈哈哈!当前的人工智能有多智障?
- mysql_upgrade 升级_采用MySQL_upgrade升级授权表方式升级
- 中间件和微服务,Docker以及原生云架构的关系
- Windows环境下搭建Tomcat
- Chrome谷歌浏览器新功能 删除主题更方便
- clipse中Access restriction: The type ‘XXX’ is not API 解决
- lock是悲观锁还是乐观锁_图文并茂的带你彻底理解悲观锁与乐观锁
- 图像处理领域的国际会议及期刊
- Guava学习笔记(六):Immutable(不可变)集合
- jpg格式的矢量化arcgis_arcgis将jpg矢量化,带坐标导出TIFF格式,再导入cad的方法...
- 年面向大学生的 9 个最佳 Chrome 扩展程序
- 广东省教育局 计算机,广东省教育厅关于公布第十七届广东省中小学电脑制作活动获奖结果的通知...
- PowerDesigner和PDMan数据库表设计工具的简单使用
- 保研被鸽,去了自己不理想的学校怎么办?
- 仙人掌之歌——大规模高速扩张(3)
- 如何设置html的背景效果,背景图片的透明度如何设置(CSS)
- 脚本化HTTP——AJax
- html5充值页面(Vue)
- Unicode 编码范围和中文编码范围
- ucosii操作系统和linux,请高手介绍下uCOSII和Linux的差异?