历史:Pivotal公司2014年发布 Spring Boot
特性:简化Spring应用的初始搭建过程和开发过程、可以打成可运行的Jar包(内嵌Tomcat)
原理:通过starter封装来减少配置;通过自动扫描被注解的类和方法来装配Bean,取代xml配置
概念
YAML:YAML Ain’t Markup Language,Clark Evans在2001年发表了这种语言
Spring Boot 应用搭建
1、到Spring官网打开 Spring Initializr,配置依赖Web,下载初始化项目,项目名以Demo为例
2、用IDEA打开,右侧“Maven Projects”添加pom.xml,加载完依赖以后才会显示完整目录
3、属性配置 resources/application.properties
server.port=8081 # 端口
server.context-path=/myapp # 路径前缀
server.error.path=/error # 出错跳转
server.session-timeout=60 # 会话超时时间
server.tomcat.uri-encoding=UTF-8
server.tomcat.basedir=/temp # 默认为 /tmp,/tmp下的目录长时间不访问的话,会被删除
spring.mvc.async.request-timeout=20000 # 请求超时时间
4、新建Controller
MyController.java
@RestController
public class MyController {
@Value("${server.port}") // 引用配置的值
private String port;
@RequestMapping("/hello")
public String Hello(){
return "Hello World";
}
}
5、运行DemoApplication.java
里面的@SpringBootApplication包含了@EnableAutoConfiguration,实现Bean自动装配
6、访问 http://localhost:8081/hello
打包与运行
打包:mvn package
运行:java -jar demo.jar
yum配置
application.properties 改成 application.yml
server:
port: 8081
spring:
servlet:
multipart:
enabled: true
max-file-size: 30MB
max-request-size: 30MB # 最大上传尺寸
content: "port is ${port}" # 引用前面定义的值
配置类
@Configuration
@MapperScan("Mapper所在包") // 简化 MapperScannerConfigurer 配置
public class Configuration{
// 用注解方法的方式来装载Bean
@Bean
public FilterRegistrationBean corsFilter() { // 允许跨域配置
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin(CorsConfiguration.ALL);
config.addAllowedHeader(CorsConfiguration.ALL);
config.addAllowedMethod("OPTIONS"); // AllowedMethod 必须罗列,而不能用通配符 *
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}
}
AOP方式记日志
1、配置Maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2、切片类
@Aspect
@Component
public class MyAspect {
@Before("execution(public * com.hogen.demo.controllers.MyController.*(..))") // 切点
public void log(JoinPoint joinPoint){
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
log(request.getRequestURI()); // 获取请求信息
log(joinPoint.getSignature().getName()); // 获取目标方法的信息
}
@After("execution(public * com.hogen.demo.controllers.MyController.*(..))")
public void doAfter(){ }
@AfterReturning(pointcut="execution(public * com.hogen.demo.controllers.MyController.*(..))", returning = "object")
public void afterReturn(Object object){ // 处理返回值
log(object.toString());
}
}
统一返回格式
1、结果类
public class Result<T> {
@JsonIgnore // 使得@ResponseBody忽略这个字段。这个注解由Jackson提供,Jackson还提供别的字段处理注解
private Integer code;
private String msg;
private T data;
}
2、异常处理类
```java
@ControllerAdvice
public class ExceptionHandle {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result handle(Exception e){
Result result = new Result();
result.setCode(1); // code也需要定制的话,可以扩展RuntimeException,增加code成员。Controller抛出new MyException(2, "我是异常"),这里就可以获取code
result.setMsg(e.getMessage());
result.setData(null);
return result;
}
@ExceptionHandler(value = MethodArgumentNotValidException.class) // 根据特定异常,返回特定信息
@ResponseBody
public RestfulResult handle(MethodArgumentNotValidException e) {
return new Result(100, "参数错误");
}
}
3、Controller
@RestController // 等效于 @Controller + @ResponseBody
public class MyController {
@RequestMapping("/hello")
public Result<String> Hello() throws Exception{ // 正常返回
Result result = new Result();
result.setCode(0);
result.setMsg("没事");
result.setData("Hello World");
return result;
}
@RequestMapping("/hello1")
public Result<String> Hello1() throws Exception{ // 异常返回
throw new Exception("我是异常"); // 会被捕获交给异常处理类
}
}
定时任务
@EnableScheduling
@Component
public class MyJobs {
@Scheduled(fixedRate = 3000) // 隔3000毫秒
@Scheduled(cron = "cron表达式") // cron表达式生成器 http://cron.qqe2.com/
public void task(){
System.out.println(44);
}
}
异步方法
1、含有异步方法的类
@Component
@EnableAsync
public class AsyncTasks {
@Async
public Future<Boolean> job() throws Exception{
Thread.sleep(1000);
System.out.println(0);
return new AsyncResult<>(true);
}
@Async
public Future<Boolean> task(){
System.out.println(1);
return new AsyncResult<>(true);
}
}
2、使用
@Autowired
private AsyncTasks asyncTasks;
// 两个异步方法并行
Future<Boolean> future1 = asyncTasks.job();
Future<Boolean> future2 = asyncTasks.task();
while (!future1.isDone() || !future2.isDone()){
Thread.sleep(10);
}
return "结束";
拦截器
注册拦截器
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurationSupport {
@Override
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(new RoleInterceptor()).addPathPatterns("/**");
super.addInterceptors(registry);
}
}
场景 Profile
分配置方法一:resources下放四个文件application.yml、application-dev.yml、application-test.yml、application-prod.yml
分配置方法二:只写一个文件,以---隔开
spring:
profiles:
active: prod
---
spring:
profiles: dev
server:
port: 8080
---
spring:
profiles: test
server:
port: 8081
分配在方法三:要在不同环境使用不同Bean,可以加注解 @Profile("prod"),与@Configuration和@Component配合使用
场景激活方法一:application.yml
spring:
profiles:
active: dev
场景激活方法二:java -jar springbootdemo.jar -- spring.profiles.active=dev
场景激活方法三:IDEA中配置SpringBoot启动参数--spring.profiles.active=dev
这里是启动时指定环境,要打包时指定环境,可以使用Maven profile
打war包,部署到Tomcat
1、pom.xml
<packaging>war</packaging>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
2、入口Java类
public class XxxxApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(XxxxApplication .class);
}
}
3、指定启动的profile:
新建 tomcat/bin/setenv.sh
export JAVA_OPTS="-Dspring.profiles.active=prod"
4、打出来的war文件,文件名改为ROOT.war,放到tomcat/webapps 下
HTTPS
1、把keystore文件 或 pfx文件 放入 resources 目录
2、配置 application.yml
server:
port: 443
ssl:
key-store: classpath:文件名.keystore
key-store-type: JKS // 或pfx证书对应为 PKCS12
key-alias: 别名
key-store-password: keystore密码
如果SpringBoot打成war包部署道Tomcat,则需要在Tomcat配置https
网友评论