spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。


Spring boot的特点

1. 创建独立的Spring应用程序
2. 嵌入的Tomcat,无需部署WAR文件
3. 简化Maven配置
4. 自动配置Spring
5. 提供生产就绪型功能,如指标,健康检查和外部配置
6. 绝对没有代码生成和对XML没有要求配置


Spring boot的优点

spring boot 可以支持你快速的开发出 restful 风格的微服务架构

自动化确实方便,做微服务再合适不过了,单一jar包部署和管理都非常方便。只要系统架构设计合理,大型项目也能用,加上nginx负载均衡,轻松实现横向扩展

spring boot 要解决的问题, 精简配置是一方面, 另外一方面是如何方便的让spring生态圈和其他工具链整合(比如Redis, email, elasticsearch)


Spring boot的使用

1、maven配置文件


[html] view plain copy 在CODE上查看代码片派生到我的代码片

  1. <?xml version="1.0" encoding="UTF-8"?>  

  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  

  3.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  

  4.     <modelVersion>4.0.0</modelVersion>  

  5.   

  6.     <groupId>org.springboot.sample</groupId>  

  7.     <artifactId>spring-boot-sample</artifactId>  

  8.     <version>0.0.1-SNAPSHOT</version>  

  9.     <packaging>war</packaging>  

  10.     <name>spring-boot-sample</name>  

  11.     <description>Spring Boot Sample Web Application</description>  

  12.     <parent>  

  13.         <groupId>org.springframework.boot</groupId>  

  14.         <artifactId>spring-boot-starter-parent</artifactId>  

  15.         <version>1.3.2.RELEASE</version>  

  16.         <relativePath />   

  17.     </parent>  

  18.     <properties>  

  19.         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  

  20.         <java.version>1.8</java.version>  

  21.     </properties>  

  22.     <dependencies>  

  23.         <dependency>  

  24.             <groupId>org.springframework.boot</groupId>  

  25.             <artifactId>spring-boot-starter-web</artifactId>  

  26.         </dependency>  

  27.         <!-- MYSQL -->  

  28.         <dependency>  

  29.             <groupId>mysql</groupId>  

  30.             <artifactId>mysql-connector-java</artifactId>  

  31.         </dependency>  

  32.         <!-- Spring Boot JDBC -->  

  33.         <dependency>  

  34.             <groupId>org.springframework.boot</groupId>  

  35.             <artifactId>spring-boot-starter-jdbc</artifactId>  

  36.         </dependency>  

  37.         <dependency>  

  38.             <groupId>org.springframework.boot</groupId>  

  39.             <artifactId>spring-boot-configuration-processor</artifactId>  

  40.             <optional>true</optional>  

  41.         </dependency>  

  42.     </dependencies>  

  43.     <build>  

  44.         <plugins>  

  45.             <plugin>  

  46.                 <groupId>org.springframework.boot</groupId>  

  47.                 <artifactId>spring-boot-maven-plugin</artifactId>  

  48.             </plugin>  

  49.         </plugins>  

  50.     </build>  

  51. </project>  


2、application类



[java] view plain copy 在CODE上查看代码片派生到我的代码片

  1. @SpringBootApplication  

  2. @ServletComponentScan  

  3. public class SpringBootApplication extends SpringBootServletInitializer {  

  4.   

  5.     private static final Logger logger = LoggerFactory.getLogger(SpringBootSampleApplication.class);  

  6.     public static void main(String[] args) {  

  7.         SpringApplication.run(SpringBootSampleApplication.class, args);  

  8.     }  

  9. }  


3、配置类



[java] view plain copy 在CODE上查看代码片派生到我的代码片

  1. @Repository  

  2. @Component  

  3. @Configuration  

  4. public class MyWebAppConfigurer extends WebMvcConfigurerAdapter implements EnvironmentAware{  

  5.     private static final Logger logger = LoggerFactory.getLogger(MyWebAppConfigurer.class);  

  6.     private RelaxedPropertyResolver propertyResolver;  

  7.     @Override  

  8.     public void addInterceptors(InterceptorRegistry registry) {  

  9.         // 多个拦截器组成一个拦截器链  

  10.         // addPathPatterns 用于添加拦截规则  

  11.         // excludePathPatterns 用户排除拦截  

  12.         registry.addInterceptor(new MyInterceptor1()).addPathPatterns("/**");  

  13.         registry.addInterceptor(new MyInterceptor2()).addPathPatterns("/**");  

  14.         super.addInterceptors(registry);  

  15.     }  

  16.     @Override  

  17.     public void addResourceHandlers(ResourceHandlerRegistry registry) {  

  18.         registry.addResourceHandler("/res/**").addResourceLocations("classpath:/res/");  

  19.         // 可以直接使用addResourceLocations 指定磁盘绝对路径,同样可以配置多个位置,注意路径写法需要加上file:  

  20.         registry.addResourceHandler("/imgs/**").addResourceLocations("file:D:/imgs/");  

  21.         super.addResourceHandlers(registry);  

  22.     }  

  23. <strong>}</strong>  



4、添加filter


[java] view plain copy 在CODE上查看代码片派生到我的代码片

  1. @WebFilter(filterName="myFilter",urlPatterns="/*")  

  2. public class MyFilter implements Filter {  

  3.     @Override  

  4.     public void destroy() {  

  5.         System.out.println("过滤器销毁");  

  6.     }  

  7.     @Override  

  8.     public void doFilter(ServletRequest request, ServletResponse response,  

  9.             FilterChain chain) throws IOException, ServletException {  

  10.         System.out.println("执行过滤操作");     

  11.         chain.doFilter(request, response);  

  12.     }  

  13.     @Override  

  14.     public void init(FilterConfig config) throws ServletException {  

  15.         System.out.println("过滤器初始化");  

  16.     }  

  17. }  


5、controller

[java] view plain copy 在CODE上查看代码片派生到我的代码片

  1. @RestController  

  2. @RequestMapping("/hello")  

  3. public class HelloController {  

  4.     @RequestMapping("/info")  

  5.     public Map<String, String> getInfo(@RequestParam String name) {  

  6.         Map<String, String> map = new HashMap<>();  

  7.         return map;  

  8.     }     

  9. }  


6、service



[java] view plain copy 在CODE上查看代码片派生到我的代码片

  1. @Service  

  2. public class HelloWorldService {  

  3.     public String getHelloMessage() {  

  4.         return "Hello world";  

  5.     }  

  6. }  


7、全局异常处理



[java] view plain copy 在CODE上查看代码片派生到我的代码片

  1. @ControllerAdvice  

  2.  public class GlobalExceptionHandler {  

  3.      @ExceptionHandler(RuntimeException.class)  

  4.      @ResponseBody //在返回自定义相应类的情况下必须有,这是@ControllerAdvice注解的规定  

  5.      public MyExceptionResponse exceptionHandler(RuntimeException e, HttpServletResponse response) {  

  6.          

  7.          return resp;  

  8.      }  

  9.  }  

说明:
@ControllerAdvice是controller的一个辅助类,最常用的就是作为全局异常处理的切面类
@ControllerAdvice可以指定扫描范围
@ControllerAdvice约定了几种可行的返回值,如果是直接返回model类的话,需要使用@ResponseBody进行json转换
1、返回String,表示跳到某个view
2、返回modelAndView
3、返回model + @ResponseBody


8、添加被其他配置使用的bean


[java] view plain copy 在CODE上查看代码片派生到我的代码片

  1. @Bean  

  2. public PageHelper pageHelper(DataSource dataSource) {  

  3.     PageHelper pageHelper = new PageHelper();  

  4.     return pageHelper;  

  5. }  



9、添加数据加载类


[java] view plain copy 在CODE上查看代码片派生到我的代码片

  1. @Component  

  2. public class MyStartupRun implements CommandLineRunner {  

  3.     @Override  

  4.     public void run(String... args) throws Exception {  

  5.         System.out.println(">>>>>>>>>>>>>>>服务启动执行");  

  6.     }  

  7. }  

该组件在项目启动时会立即执行