Java 杂谈

spring boot介绍及使用详解

2019-04-10  本文已影响0人  程序人生a

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配置文件

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

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

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

<modelVersion>4.0.0</modelVersion>

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

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

<version>0.0.1-SNAPSHOT</version>

<packaging>war</packaging>

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

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

<parent>

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

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

<version>1.3.2.RELEASE</version>

<relativePath />

</parent>

<properties>

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

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

</properties>

<dependencies>

<dependency>

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

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

</dependency>

<!-- MYSQL -->

<dependency>

<groupId>mysql</groupId>

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

</dependency>

<!-- Spring Boot JDBC -->

<dependency>

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

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

</dependency>

<dependency>

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

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

<optional>true</optional>

</dependency>

</dependencies>

<build>

<plugins>

<plugin>

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

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

</plugin>

</plugins>

</build>

</project>

2、application类

@SpringBootApplication

@ServletComponentScan

public class SpringBootApplication extends SpringBootServletInitializer {

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

    public static void main(String[] args) {

SpringApplication.run(SpringBootSampleApplication.class, args);

}

}

3、配置类

@Repository

@Component

@Configuration

public class MyWebAppConfigurer extends WebMvcConfigurerAdapter implements EnvironmentAware{

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

private RelaxedPropertyResolver propertyResolver;

@Override

public void addInterceptors(InterceptorRegistry registry) {

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

// addPathPatterns 用于添加拦截规则

// excludePathPatterns 用户排除拦截

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

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

super.addInterceptors(registry);

}

@Override

public void addResourceHandlers(ResourceHandlerRegistry registry) {

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

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

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

super.addResourceHandlers(registry);

}

}

4、添加filter

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

public class MyFilter implements Filter {

    @Override

    public void destroy() {

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

    }

    @Override

    public void doFilter(ServletRequest request, ServletResponse response,

            FilterChain chain) throws IOException, ServletException {

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

        chain.doFilter(request, response);

    }

    @Override

    public void init(FilterConfig config) throws ServletException {

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

    }

}

5、controller

@RestController

@RequestMapping("/hello")

public class HelloController {

@RequestMapping("/info")

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

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

return map;

}

}

6、service

@Service

public class HelloWorldService {

public String getHelloMessage() {

return "Hello world";

}

}

7、全局异常处理

@ControllerAdvice

public class GlobalExceptionHandler {

    @ExceptionHandler(RuntimeException.class)

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

    public MyExceptionResponse exceptionHandler(RuntimeException e, HttpServletResponse response) {

        return resp;

    }

}

说明:

@ControllerAdvice是controller的一个辅助类,最常用的就是作为全局异常处理的切面类

@ControllerAdvice可以指定扫描范围

@ControllerAdvice约定了几种可行的返回值,如果是直接返回model类的话,需要使用@ResponseBody进行json转换

1、返回String,表示跳到某个view

2、返回modelAndView

3、返回model + @ResponseBody

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

@Bean

public PageHelper pageHelper(DataSource dataSource) {

PageHelper pageHelper = new PageHelper();

return pageHelper;

}

9、添加数据加载类

@Component

public class MyStartupRun implements CommandLineRunner {

    @Override

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

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

    }

}

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

另:给大家推荐一个Java架构进阶群777584112,(群内有高可用、高并发、高性能及分布式、Jvm性能调优、Spring,MyBatis,Netty源码分析,Redis,Kafka,Mysql,Zookeeper,Tomcat,Docker,Dubbo,Nginx等多个知识点的资料免费分享)

上一篇下一篇

猜你喜欢

热点阅读