一、yml配置文件的使用
SpringBoot 默认读取会 application.yml和application.properties文件,yml文件比properties更加简洁,结构清晰。我们可以在配置文件中修改SpringBoot默认的端口号和项目的根路径,如下所示
二、通过@Value自定义参数获取
1、配置文件中书写自定义参数如下
2、在代码中获取如下:
@RestController
@RequestMapping(value = "/myparams")
public class myParamsController {
/**
* 通过${配置文件中的key}获取值
*/
@Value("${myparams.name}")
private String name;
@Value("${myparams.code}")
private Integer code;
@Value("${myparams.hello.world}")
private String helloWorld;
@RequestMapping(value = "/test")
public Map test(){
Map map = new HashMap<>();
map.put("name",name);
map.put("code",code);
map.put("helloWorld",helloWorld);
return map;
}
}
3、测试访问如下:
三、多环境配置
一般公司都分为开发环境,测试环境,生产环境。不同的环境数据库和一些配置可能不同,我们可以通过下面的方法进行多环境配置(指定读取某个配置文件);
1、建立如下配置文件,,test测试环境,prod生产环境
application-dev.yml开发环境:
################开发环境#####################
http_url: www.dev.com
application-test.yml测试环境:
################测试环境#####################
http_url: www.test.com
application-prod.yml生产环境:
################生产环境#####################
http_url: www.prod.com
然后在application.yml中指定配置文件
可以通过上面读取@Value的例子进行测试。
四、使用Spring自带的定时任务
1、在启动类上添加@EnableScheduling启动定时任务
@SpringBootApplication
@MapperScan(basePackages = "com.caofanqi.mapper")
@EnableScheduling //启动定时任务
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
2、@Scheduled创建定时任务
package com.caofanqi.scheduled;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class ScheduledTaskTest {
@Scheduled(cron = "0/5 * * * * ?")
public void test() {
log.info("定时任务,每五秒执行一次!!!");
}
}
3、启动项目如下所示
五、使用Spring自带的异步调用
1、在启动类上添加@EnableAsync启动异步调用
@SpringBootApplication
@MapperScan(basePackages = "com.caofanqi.mapper")
@EnableScheduling //启动定时任务
@EnableAsync //启动异步调用
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
2、在方法上添加 @Async 表示该方法异步调用
@Async //异步调用
public void testAsync(String id) {
log.info("2、异步方法开始运行...");
//模拟处理业务
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("3、处理id :" + id +"....异步任务完成...");
}
3、Controller
@Slf4j
@RestController
@RequestMapping(value = "/async")
public class asyncController {
@Autowired
private UserService userService;
@RequestMapping(value = "/test",method = RequestMethod.GET)
public String test(String id){
log.info("1、asyncController 处理请求");
userService.testAsync(id);
log.info("4、asyncController 处理完成");
return "success";
}
}
4、测试如下,postman发出请求后,没有等待,直接得到了响应
六、拦截器使用
1、定义拦截器类 implements HandlerInterceptor
/**
* 定义拦截器类 implements HandlerInterceptor
*/
@Slf4j
public class LoginIntercept implements HandlerInterceptor {
//前置拦截
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
log.info("开始拦截登录请求....");
String token = request.getParameter("token");
if (StringUtils.isEmpty(token)) {
response.getWriter().println("not found token");
return false;
}
return true;
}
}
2、注册拦截器
@Configuration
public class WebAppConfig {
@Bean
public WebMvcConfigurer WebMvcConfigurer() {
return new WebMvcConfigurer() {
public void addInterceptors(InterceptorRegistry registry) {
// addPathPatterns 用于添加拦截规则
// excludePathPatterns 用户排除拦截
registry.addInterceptor(new LoginIntercept()).addPathPatterns("/**");
}
};
}
}
拦截器与过滤器区别
拦截器是AOP( Aspect-Oriented Programming)的一种实现,底层通过动态代理模式完成。
①拦截器是基于java的反射机制的,而过滤器是基于函数回调。
②拦截器不依赖于servlet容器,而过滤器依赖于servlet容器。
③拦截器只能对Controller请求起作用,而过滤器则可以对几乎所有的请求起作用。
④在Controller的生命周期中,拦截器可以多次被调用,而过滤器只能在容器初始化时被调用一次。
过滤器应用场景:设置编码字符、过滤铭感字符
拦截器应用场景:拦截未登陆用户、审计日志
项目源码:https://gitee.com/itcaofanqi/CaoFanqiStudyRepository/tree/master/stuspringboot/