从Java EE5规范开始,Servlet增加了两个影响Servlet生命周期的注解(Annotation):@PostConstruct和@PreConstruct。
被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器调用一次,类似于Serclet的inti()方法。被@PostConstruct修饰的方法会在构造函数之后,init()方法之前运行。
被@PreConstruct修饰的方法会在服务器卸载Servlet的时候运行,并且只会被服务器调用一次,类似于Servlet的destroy()方法。被@PreConstruct修饰的方法会在destroy()方法之后运行,在Servlet被彻底卸载之前。
之前运行@PostConstruct出现问题,发现在@PostConstruct修饰的方法结束之前,web应用无法正常执行,无法处理web请求。
Spring Boot应用程序在启动后,会遍历CommandLineRunner接口的实例并运行它们的run方法。也可以利用@Order注解(或者实现Order接口)来规定所有CommandLineRunner实例的运行顺序。不过实现CommandLineRunner不会影响其他web请求。
二、@Scheduled
在SpringBoot中使用@Scheduled需要使用@EnableScheduling注解,修改服务器时间后到规定时间不执行【Scheduled中有一个任务按照间隔时间来执行Scheduled】,后续观察是否可以修正到正常的时间。Scheduled只记录相对时间来执行调度中间并不会校对时间,所以修改系统的小伙伴需要重启应用。
在Spring中调用接口可以使用restTemplate比较方便,调用上传、下载的接口写法比较麻烦,我在这里记录一下上传文件的代码
根据上传接口需要的参数传递参数:返回结果用com.alibaba.fastjson.JSONObject做格式转换。
下载因为是数据流所以应该是byte[]数组 (此处百度测试)
FileSystemResource resource = new FileSystemResource(new File(zipPath)); MultiValueMap<String, Object> param = new LinkedMultiValueMap<>(); param.add("file", resource); param.add("fileClass", InterfaceConstant.FILE_CLASS); HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String,Object>>(param); String url = "http://" + InterfaceConstant.FILE_SERVER_NAME + "/" + InterfaceConstant.FILE_UPLOAD_FUN; ResponseEntity<Response> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Response.class); Response body = response.getBody(); System.out.println("上传文件返回结果:" + body); Attachment attachment = response.getBody().getObjectBody(Attachment.class);