首先,我是参考了这个博文。
https://blog.csdn.net/valada/article/details/80892573
什么是 Spring Boot
官方的说法是:
Spring Boot 是由 Pivotal 团队提供的基于 Spring 的全新框架,其设计目的是为了简化 Spring 应用的搭建和开发过程。该框架遵循“约定大于配置”原则,采用特定的方式进行配置,从而使开发者无需定义大量的 XML 配置。通过这种方式,Spring Boot 致力于在蓬勃发展的快速应用开发领域成为领导者
因个人从14年就一直使用spring的框架,在spring出世之前,深知配置文件冗杂的累。
一句话:springboot解放了我们的配置文件,将更多的时间专注于业务实现中。简化项目搭建,内置了tomcat。
除了上述优点外,springboot还有其它优点,请见下面。
1.数据库配置,文件上传大小限制等,可通过application.properties设置。
2.方便了我们的打包操作,这个是重点。
因为我以前打包是通过在application.properties多个配置设置,手动注释或放开来达到目的,容易出错。比如有开发环境,有测试环境,还有生产环境。然后根据发布的服务器不同配置文件的配置又不同等。所以这个是重点。
在Spring Boot中多环境配置文件名需要满足application-{profile}.properties的格式,其中{profile}对应你的环境名字,比如:
application-dev.properties:开发环境
application-test.properties:测试环境
application-prod.properties:生产环境
至于哪个具体的配置文件会被加载,需要在application.properties文件中通过spring.profiles.active属性来设置,其值对应{profile}值。
比如下面是我的。
将不同的环境配置写在各个配置文件里就行了。
3.可设全局变量
@Value
通常情况下,我们需要定义一些全局变量,都会想到的方法是定义一个 public static 变量,在需要时调用,是否有其他更好的方案呢?答案是肯定的。如下:
@Value("${spring.profiles.active}")
String active;
spring.profiles.active 就是我们在 application.properties里面定义的属性,我们可以自定义任意属性名,通过 @Value
注解就可以将其取出来。
它的好处如下:
1.定义在配置文件里,变量发生变化,无需修改代码。
2.变量交给Spring来管理,性能更好。
4.springboot可以管理拦截器
创建一个拦截器类:ApiInterceptor,并实现 HandlerInterceptor 接口
public class ApiInterceptor implements HandlerInterceptor {
//请求之前
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
System.out.println("进入拦截器");
return true;
}
//请求时
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
//请求完成
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
@SpringBootConfiguration
注解的类继承 WebMvcConfigurationSupport 类,并重写 addInterceptors 方法,将 ApiInterceptor 拦截器类添加进去,代码如下:
@SpringBootConfigurationpublic
class WebConfig extends WebMvcConfigurationSupport {
@Override
protected void addInterceptors(InterceptorRegistry registry) {
super.addInterceptors(registry);
registry.addInterceptor(new ApiInterceptor());
}
}
springboot拦截器的框架就已写完了,具体业务实现自行补脑。
5.异常处理
可参考:
https://www.cnblogs.com/xuwujing/p/10933082.html
SpringBoot的项目已经对有一定的异常处理了,但是对于我们开发者而言可能就不太合适了,因此我们需要对这些异常进行统一的捕获并处理。SpringBoot中有一个ControllerAdvice
的注解,使用该注解表示开启了全局异常的捕获,我们只需在自定义一个方法使用ExceptionHandler
注解然后定义捕获异常的类型即可对这些捕获的异常进行统一的处理。
@ControllerAdvice //全局异常补获
public class MyExceptionHandler {
@ExceptionHandler(value =Exception.class)
public String exceptionHandler(Exception e){
System.out.println("未知异常!原因是:"+e);
return e.getMessage();
}
}
这里就不作赘述了,大家可以参考这位博主的文章,写的非常好。
6.单元测试
@SpringBootTest(classes = DemoApplication.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class TestDB {
@Test
public void test() {
}
}
以上只是单元测试的简单框架,详细深入请参考:
https://blog.csdn.net/sz85850597/article/details/80427408
在此大功告成。