SpringBoot框架

Day01笔记

一、Spring 4.x 基本注解形式开发配置

​ Spring框架从4.x版本开始推荐使用注解形式来对java 应用程序进行开发与配置,并且可以完全替代原始的Xml+注解形式的开发。 在使用注解形式进行项目开发与环境配置时,Spring 框架提供了针对环境配置与业务bean开发相关注解。

1.注解
1.1声明 Bean 注解

@Component 组件 没有明确规定其角色,作用在类级别上声明当前类为一个业务组件,被Spring Ioc 容器维护;

@Service 在业务逻辑层(Service 层)类级别进行声明;

@Repository 在数据访问层(dao 层) 类级别声明;

@Controller

在展现层(MVC) 使用 标注当前类为一个控制器注入Bean

1.2 Set方法或属性上声明注解

@AutoWired Spring 官方提供注解

@Inject JSR-330 提供注解(标准制定方)

@Resource JSR-250 提供注解

1.3 Spring4.x 中配置与获取Bean注解

@Configuration:作用与类上,将当前类声明为一个配置类,相当于一个 xml 配置文件

@ComponentScan:自动扫描指定包下标注有@Repository,@Service,@Controller

@Component 注解的类并由 Ioc 容器进行实例化和维护

@Bean 作用与方法上,相当于 xml 文件中 声明当前方法返回值为一个 bean

@Value

2.IOC中bean的实例化与获取
2.1添加依赖
 <dependency> 
      <groupId>org.springframework</groupId> 
      <artifactId>spring-context</artifactId> 
      <version>4.3.2.RELEASE</version> 
  </dependency> 

<build>
      <plugins>
          <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-compiler-plugin</artifactId>
              <version>2.3.2</version>
              <configuration>
                  <source>1.8</source>
                  <target>1.8</target>
                  <encoding>utf-8</encoding>
              </configuration>
          </plugin>
      </plugins>

  </build>
2.2源代码

com.shsxt.dao.UserDao

@Repository
public class UserDao {

    public void test(){
        System.out.println("test......userDao.....");
    }
}

com.shsxt.service.UserService

@Service
public class UserService {

    @Resource
    private UserDao userDao;

    public void test(){
        System.out.println("service...test。。。。");
        userDao.test();
    }
}

com.shsxt.config.IocConfig

@Configuration
@ComponentScan("com.shsxt")
public class IocConfig {
    
}

测试类

public class TestUser {
    public static void main(String[] args) {

	ApplicationContext ac=new 		 AnnotationConfigApplicationContext(IocConfig.class);
	//得到UserDao的bean实例化
    UserDao userDao= (UserDao) ac.getBean("userDao");
        userDao.test();
	//得到UserService的bean实例化
        UserService userService= (UserService) ac.getBean("userService");
        userService.test();
        //是否是单例
        System.out.println(ac.isSingleton("iocConfig"));
    }
3.读取外部配置文件(数据库)

读取jdbc.properties文件

## dev开发环境
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
jdbc.uname=root
jdbc.password=123456

com.shsxt.datasource.MyDataSource

public class MyDataSource {

    @Value("${jdbc.driver")
    private String driverClass;
    
    @Value("${jdbc.url}")
    private String url;
    
    @Value("${jdbc.uname}")
    private String userName;
    
    @Value("${jdbc.password}")
    private String password;

    public MyDataSource() {
    }

    public MyDataSource(String driverClass, String url, String userName, String password) {
        this.driverClass = driverClass;
        this.url = url;
        this.userName = userName;
        this.password = password;
    }

    public String getDriverClass() {
        return driverClass;
    }

    public void setDriverClass(String driverClass) {
        this.driverClass = driverClass;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "MyDataSource{" +
                "driverClass='" + driverClass + '\'' +
                ", url='" + url + '\'' +
                ", userName='" + userName + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

com.shsxt.config.IocConfig

@Configuration
@ComponentScan("com.shsxt")
@PropertySource(value = {"classpath:jdbc.properties"})
public class IocConfig {

    @Bean
    public MyDataSource myDataSource(){
        return new MyDataSource();
    }
    
}

测试类

public class TestUser {
    public static void main(String[] args) {
        
        ApplicationContext ac=new AnnotationConfigApplicationContext(IocConfig.class);
        
       IocConfig iocConfig=ac.getBean(IocConfig.class);
        
       System.out.println(iocConfig);
        
       System.out.println(iocConfig.myDataSource());

    }
}

4.组合注解与元注解
@Configuration

拥有Component 注解功能,即配置类本身也是一个被Ioc维护的单例Bean.

@SxtCompScan

拥有元注解@Configuration + @ComponentScan二者功能

使用:@SxtCompScan(“com.shsxt”)

二、Spring Mvc零配置创建与部署

1.添加依赖
 <!-- spring web --> 
<dependency> 
  <groupId>org.springframework</groupId> 
  <artifactId>spring-web</artifactId> 
  <version>4.3.2.RELEASE</version> 
</dependency> 
 
<!-- spring mvc --> 
<dependency> 
  <groupId>org.springframework</groupId> 
  <artifactId>spring-webmvc</artifactId> 
  <version>4.3.2.RELEASE</version> 
</dependency> 
 
<!-- web servlet --> 
<dependency> 
  <groupId>javax.servlet</groupId> 
  <artifactId>javax.servlet-api</artifactId> 
  <version>3.0.1</version> 
</dependency> 

<build>
    <finalName>springBoot02</finalName>
      <plugins>
          <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-compiler-plugin</artifactId>
              <version>2.3.2</version>
              <configuration>
                  <source>1.8</source>
                  <target>1.8</target>
                  <encoding>utf-8</encoding>
              </configuration>
          </plugin>
      </plugins>
  </build>
2.源代码

com.shsxt.controller.HelloController

@Controller
public class HelloController {

    @RequestMapping("/index")
    public String index(){
        return "index";
    }
    
}

添加视图

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
   hello spring
</body>
</html>

Mvc环境配置信息添加

com.shsxt.config.MvcConfig

@Configuration
@EnableWebMvc
@ComponentScan("com.shsxt")
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Bean
    //加载视图解器 bean 配置
    public InternalResourceViewResolver viewResolver(){
        InternalResourceViewResolver viewResolver=new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        return  viewResolver;
    }
}

应用配置加载接口实现

com.shsxt.WebInitializer

public class WebInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext ctx=new AnnotationConfigWebApplicationContext();
        // 注册 Mvc 配置信息
        ctx.register(MvcConfig.class);
        // 设置 ServletContext 上下文信息
        ctx.setServletContext(servletContext);
        // 配置转发器 Dispatcher
        ServletRegistration.Dynamic
                servlet=servletContext.addServlet("dispatcher",new DispatcherServlet(ctx));
        servlet.addMapping("/");
        // 启动时即实例化 Bean
        servlet.setLoadOnStartup(1);
    }
}
3.IOC实例化 、生效拦截器

com.shsxt.config.MvcConfig

@Configuration
@EnableWebMvc
@ComponentScan("com.shsxt")
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Bean
    public InternalResourceViewResolver viewResolver(){
        InternalResourceViewResolver viewResolver=new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        return  viewResolver;
    }


    // IOC 实例化 LoginInterceptor
    @Bean
    public LoginInterceptor loginInterceptor(){
        return new LoginInterceptor();
    }


    // 生效拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/user/login");
    }
    
}

com.shsxt.interceptors.LoginInterceptor

public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("登录拦截器...");
        return true;
    }
    
}

com.shsxt.controller.UserController

@Controller
public class UserController {

    @RequestMapping("user/login")
    public void login(){
        System.out.println("用户登录方法...");
    }
}

三、Spring Boot 概念介绍特点、普通项目创建

1.概念

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

​ Spring Boot 能够让项目快速运行起来,同时借助Spring Boot可以快速创建web 应用并独立进行部署(jar包 war 包方式,内嵌servlet 容器),同时借助Spring Boot 在开发应用时可以不用或很少去进行相关xml环境配置,简化了开发,大大提高项目开发效。

2.特点

创建独立Spring应用程序、嵌入式Tomcat,Jetty容器、无需部署WAR包、简化Maven及Gradle配置、尽可能的自动化配置Spring、直接植入产品环境下的实用功能,比如度量指标、健康检查及扩展配置、无需代码生成及XML配置等 。

​ Spring Boot不止对web应用程序做了简化,还提供一系列的依赖包来把其它一些工作做成开箱即用。

3.spring boot 普通项目创建
3.1添加依赖
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
</parent>

 <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-aop</artifactId>
  </dependency>


   <dependency>
     	<groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
   </dependency>
    <dependency>
          <groupId>c3p0</groupId>
          <artifactId>c3p0</artifactId>
          <version>0.9.1.2</version>
      </dependency>
<plugins>
          <plugin>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-maven-plugin</artifactId>
          </plugin>
</plugins>
3.2 源代码

com.shsxt.controller.HelloController

//包含 @responseBody  @Controller 组合注解
@RestController
public class HelloController {

    @RequestMapping("hello")
    public String hello(){
        return "SpringBott is so Easy!!!!";
    }

    @RequestMapping("hello02")
    public Map<String,String> hello02(){
        Map<String,String> map=new HashMap<String,String>();
        map.put("sh","东方明珠");
        map.put("hz","西湖");
        return map;
    }
}

com.shsxt.Starter

测试类

/**
 * 组合注解:@SpringBootApplication
 * 1.扫描器环境
 *      默认扫描当前类所有包以及子包
 * 2.配置类
 * 3.单例对象
 * 4.默认启用自动化配置
 *
 */
@SpringBootApplication
public class Starter {

    public static void main(String[] args) {

        SpringApplication.run(Starter.class);
        
    }
}

四、Spring Boot 核心讲解

1.入口类与@SpringBootApplication注解

注解组合:@SpringBootConfiguration、@EnableAutConfiguration、@CompentScan

2.自动配置与关闭

可在依赖包:spring-boot-autoconfigure 下看到。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Du56u3AN-1597568309951)(F:\A20200102\高级资源\SpringBoot%5CUsers%5CH1.png)]

对于@SpringBootApllication 注解源码定义中

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BEMjFRPb-1597568309954)(C:\Users\Hello Word\AppData\Roaming\Typora\typora-user-images\1585830965785.png)]

从解释中可以看到,如果想要关闭某项自动配置页也很简单,只需要加入到排除项中即可!

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KWPj3zlg-1597568309956)(C:\Users\Hello Word\AppData\Roaming\Typora\typora-user-images\1585830994345.png)]

3.自定义Banner与Banner关闭
@SpringBootApplication
public class Starter {

    public static void main(String[] args) {


        //关闭banner配置,图案

   SpringApplication springApplication=new SpringApplication(Starter.class);
        springApplication.setBannerMode(Banner.Mode.OFF);
        springApplication.run();
    }
}
4.SpringBoot配置文件

resources资源目录下添加application.properties 文件配置信息如下:

## 项目启动端口号配置 
server.port=8989 
## 项目访问上下文路径 
server.servlet.context-path=/boot 
 
 
## 日志信息打印配置 
logging.pattern.level=debug logging.pattern.console=%d [%t] %-5p [%c] - %m%n 
 
## jdbc 连接数据库 基本配置 
spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/hr?useUnicode=true&charact erEncoding=utf8 
spring.datasource.username=root spring.datasource.password=root 

resurces资源目录下添加application.yml文件配置信息:

server:
  port: 8989
  servlet:
    context-path: /springboot


#spring:
#  ## 数据源配置
#  datasource:
#    driver-class-name: com.mysql.jdbc.Driver
#    url: jdbc://ip:port/ssm
#    username: root
#    password: root
#    type: com.mchange.v2.c3p0.ComboPooledDataSource
#  ## 邮件配置
#  mail:
#    host: smtp:163.com
#    port: 21
#    username: xxx@163.com
#    password: 123456
#
#  ## freemarker
#  freemarker:
#    charset: utf-8
#    suffix: .ftl
#    prefix: /WEB-INF/views


profile配置

#server:
##  port: 8989
#  servlet:
 #   context-path: /springboot



#spring:
#  ## 数据源配置
#  datasource:
#    driver-class-name: com.mysql.jdbc.Driver
#    url: jdbc://ip:port/ssm
#    username: root
#    password: root
#    type: com.mchange.v2.c3p0.ComboPooledDataSource
#  ## 邮件配置
#  mail:
#    host: smtp:163.com
#    port: 21
#    username: xxx@163.com
#    password: 123456
#
#  ## freemarker
#  freemarker:
#    charset: utf-8
#    suffix: .ftl
#    prefix: /WEB-INF/views

## 动态选择不同环境的配置文件
spring:
  profiles:
    active: dev

application-dev.yml

server:
  port: 8989

##数据配置
datasource:
  type: com.mchange.v2.c3p0.ComboPooledDataSource
  url: jdbc://127.0.0.1:3306/ssm
  driver-class-name: com.mysql.jdbc.Driver
  username: root
  password: 123456

spring:
  ##freemarker整合配置
  freemarker:
    prefix: views/
    suffix: ftl
    charset: utf-8
   ## java mail 邮件发送
  mail:
    host: smtp.163.com
    port: 22
    username: xxx@163.com
    password: 123qwe
## 数据库分页配置
#pagehelper:
#  dialect: mysql

日志打印

@SpringBootApplication
public class Starter {
    
//定义日志
    private static Logger logger = LoggerFactory.getLogger(Starter.class);
    
    public static void main(String[] args) {

      /*  SpringApplication.run(Starter.class);*/
        logger.debug("hello springboot");
        //关闭banner配置,图案

       SpringApplication springApplication=new SpringApplication(Starter.class);
        springApplication.setBannerMode(Banner.Mode.OFF);
        springApplication.run();
    }
}

Day02笔记

一、Spring Boot web项目构建与整合Freemarker

1.创建普通工程(quickstart)
2.添加坐标依赖
<parent> 
  <groupId>org.springframework.boot</groupId> 
  <artifactId>spring-boot-starter-parent</artifactId> 
  <version>1.4.1.RELEASE</version> 
  <relativePath/>  
</parent> 
 
<dependency> 
  <groupId>org.springframework.boot</groupId> 
  <artifactId>spring-boot-starter-web</artifactId> 
</dependency> 
<dependency> 
  <groupId>org.springframework.boot</groupId> 
  <artifactId>spring-boot-starter-freemarker</artifactId> 
</dependency> 

<build>
    <plugins> 
      <plugin> 
        <groupId>org.springframework.boot</groupId> 
        <artifactId>spring-boot-maven-plugin</artifactId> 
      </plugin> 
	</plugins> 
</build>

3.freemarker全局配置

resources/application.yml

server:
  port: 8080
  servlet:
    context-path:
spring:
  freemarker:
    charset: UTF-8
    suffix:  .ftl
    template-loader-path: classpath:/views/
4.源代码

配置controller控制层

@Controller
public class IndexController {

    @RequestMapping("index")
    public String index(HttpServletRequest request){
       request.setAttribute("msg","hello springboot freemarker");
       request.setAttribute("ctx",request.getContextPath());
        return "index";
    }
}

resources/views/index.jtl

${msg}

com.shsxt.Starter

@SpringBootApplication
public class Starter{
     public static void main(String[] args) {
         
         SpringApplication.run(Starter.class);
    }
}

访问路径:http://localhost:8080/index

5.访问静态资源

路径:resources/public/css|js|images

控制层

@Controller
public class IndexController {

    @RequestMapping("index")
    public String index(HttpServletRequest request){
       request.setAttribute("msg","hello springboot freemarker");
       request.setAttribute("ctx",request.getContextPath());
        return "index";
    }
}

com.shsxt.Starter

@SpringBootApplication
public class Starter{
     public static void main(String[] args) {
         
         SpringApplication.run(Starter.class);
    }
}

index.jtl

<script type="text/javascript" src="${ctx}/js/index.js"></script>
<link  rel="stylesheet" href="${ctx}/css/index.css">
${msg}
<img src="${ctx}/images/bd_logo1.png">

访问路径:http://localhost:8080/index

6.项目打包与运行操作
6.1 jar 包部署

当 项 目 要 进 行 上 线 时 , 需 要 对 项 目 进 行 打 包 操 , 通 过 clean compile package Dmaven.test.skip=true 执行打包命令,得到待部署的项目文件

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ouVgUyjE-1597568309959)(F:\A20200102\高级资源\SpringBoot\2.png)]

如果项目packaging 为jar 打包过后生成jar 包此时如果想要以jar 文

件运行web 项目在dos 窗口执行命令 java -jar xx.jar

6.2 war 包部署
 <!--修改packing jar ... war   -->
    <packaging>war</packaging>
 <!--
            设置Tomcat 作用域provide 运行期不生效
      -->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-tomcat</artifactId>
          <scope>provided</scope>
      </dependency>

添加容器启动加载文件(类似于读取web.xml)

// 3. 继承SpringBootServletInitializer 重写configure 设置应用程序执行入口
@SpringBootApplication
public class Starter extends SpringBootServletInitializer {
     public static void main(String[] args) {
         SpringApplication.run(Starter.class);

    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(Starter.class);
    }
}

二、Spring Boot整合Mybatis

1.创建普通工程
2.添加坐标依赖
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
</parent>

 <!--web-->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
    <!--freemarker-->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-freemarker</artifactId>
      </dependency>
    <!--aop-->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-aop</artifactId>
      </dependency>
    <!--mybatis-->
      <dependency>
          <groupId>org.mybatis.spring.boot</groupId>
          <artifactId>mybatis-spring-boot-starter</artifactId>
          <version>2.1.1</version>
      </dependency>
    <!--分页插件-->
      <dependency>
          <groupId>com.github.pagehelper</groupId>
          <artifactId>pagehelper-spring-boot-starter</artifactId>
          <version>1.2.13</version>
      </dependency>
        <!--数据库-->
      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.47</version>
      </dependency>
    <!--数据源-->
    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.5.5</version>
    </dependency>

<build>
      <plugins>
          <plugin>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-maven-plugin</artifactId>
          </plugin>
      </plugins>
  </build>
3.全局配置application.yml
server:
  port: 8989
  servlet:
    context-path: /smf
spring:
  ##freemarker
  freemarker:
    template-loader-path: classpath:/views/
    charset: UTF-8
    suffix: .ftl
  ## datasource
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/mybatis?userUnicode=true&charcterEncoding=utf8&allowMultiQueries=true
    username: root
    password: 123456
## mybatis
mybatis:
  mapper-locations: classpath:/mappers/*.xml
  type-aliases-package: com.shsxt.vo;com.shsxt.query;com.shsxt.dto

## pagehelper
pagehelper:
  auto-dialect: mysql

4.源代码(整合mybatis)

com.shsxt.dao(接口)

public interface UserDao {

    @Select("select id,user_name as userName,user_pwd as userPwd,flag,create_time as createTime " +
            " from user where id=#{userId} ")
    public User queryUserByUserId(Integer userId);

    public List<User> queryUsersByUserNameLike(String userName);

    public int save(User user);

    public int update(User user);

    public int delete(Integer id);

}

com.shsxt.service

@Service
public class UserService {

    @Resource
    private UserDao userDao;


    public User queryUserByUserId(Integer userId){
        return userDao.queryUserByUserId(userId);
    }

    public List<User> queryUsersByUserNameLike(String userName){
        return userDao.queryUsersByUserNameLike(userName);
    }

    public PageInfo<User> queryUsersByUserNameLikes(Integer pageNum,Integer pageSize,String userName){
        PageHelper.startPage(pageNum,pageSize);
        return new PageInfo<User>(userDao.queryUsersByUserNameLike(userName));
    }
    
    public int saveUser(User user){

          int result=userDao.save(user);
       
          return result;
    }

    public int updateUser(User user){
        return userDao.update(user);

    }

    public int deleteUser(Integer id){
        return userDao.delete(id);
    }

}

com.shsxt.controller

@RestController
public class UserController {

 @Resource
    private UserService userService;

    @RequestMapping("user/queryUserByUserId")
    public User queryUserByUserId(Integer userId){
        return userService.queryUserByUserId(userId);
    }

    @RequestMapping("user/queryUsersByUserNameLike")
    public List<User> queryUsersByUserNameLike(String userName){
        return userService.queryUsersByUserNameLike(userName);
    }

    @RequestMapping("user/queryUsersByUserNameLikes")
    public PageInfo<User> queryUsersByUserNameLike(Integer pageNum, Integer pageSize, String userName){
        return userService.queryUsersByUserNameLikes(pageNum,pageSize,userName);
    }

}

com.shsxt.Starter

@SpringBootApplication
@MapperScan("com.shsxt.dao")
public class Starter {
    public static void main(String[] args) {
        SpringApplication.run(Starter.class);
    }
}

三、Swagger2 构建RestFul API 文档

1.添加依赖
<!--添加swagger2接口-->
      <dependency>
          <groupId>io.springfox</groupId>
          <artifactId>springfox-swagger2</artifactId>
          <version>2.9.2</version>
      </dependency>
      <dependency>
          <groupId>io.springfox</groupId>
          <artifactId>springfox-swagger-ui</artifactId>
          <version>2.9.2</version>
      </dependency>

2.实现接口RestFul引入swagger2注释声明
@RestController
public class UserController02 {

    @Resource
    private UserService userService;

    @ApiOperation("用户详情查询")

    @RequestMapping(value = "user/{userId}",method = RequestMethod.GET)
    public User queryUserByUserId(@PathVariable Integer userId){
        if(1==1){
            throw  new ParamsException("参数不合法!");
        }
        return userService.queryUserByUserId(userId);
    }


    @ApiOperation("用户多添加列表查询")
    @RequestMapping(value = "user/{userName}/list/{pageNum}/{pageSize}",method = RequestMethod.GET)

    public PageInfo<User> queryUsersByUserNameLike(@PathVariable Integer pageNum,@PathVariable Integer pageSize, @PathVariable String userName){
        return userService.queryUsersByUserNameLikes(pageNum,pageSize,userName);
    }

    @ApiOperation("用户记录添加")
    @RequestMapping(value = "user",method = RequestMethod.PUT)
    public int saveUser(@RequestBody User user){
        return userService.saveUser(user);
    }

    @ApiOperation("用户记录更新")
    @RequestMapping(value="user",method = RequestMethod.POST)
    public int updateUser(@RequestBody User user){
        return userService.updateUser(user);
    }

    @ApiOperation("用户记录删除")
    @RequestMapping(value = "user/{id}",method = RequestMethod.DELETE)
    public int delete(@PathVariable Integer id){
        return userService.deleteUser(id);
    }
}
3.swagger2配置文件

com.shsxt.config

@Configuration
@EnableSwagger2
public class Swagger2 {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.shsxt.controller"))
                                .paths(PathSelectors.any())
                                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("用户模块管理接口 API 文档参考")
                .contact("xxx公司")
                .version("1.0")
                .build();
    }
}

四、Spring Boot中统一异常、事务处理

1.事务处理

添加依赖

 <!--aop-->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-aop</artifactId>
      </dependency>

使用事务处理

 //事务配置+AOP
    @Transactional(propagation = Propagation.REQUIRED)
    public int saveUser(User user){

          int result=userDao.save(user);
          int a=1/0;
          return result;
    }
2.统一异常

com.shsxt.GlobalException

@ControllerAdvice
public class GlobalExceptionResolver {


    @ExceptionHandler(value = ParamsException.class)
    @ResponseBody
    public ResultInfo exceptionResolver01(ParamsException pe){
        ResultInfo resultInfo=new ResultInfo();
        resultInfo.setMsg(pe.getMsg());
        resultInfo.setCode(pe.getCode());
        return resultInfo;
    }

    @ExceptionHandler(value = NoLoginException.class)
    @ResponseBody
    public ResultInfo exceptionResolver02(NoLoginException ne){
        ResultInfo resultInfo=new ResultInfo();
        resultInfo.setMsg(ne.getMsg());
        resultInfo.setCode(ne.getCode());
        return resultInfo;
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultInfo exceptionResolver03(){
        ResultInfo resultInfo=new ResultInfo();
        resultInfo.setMsg("failed");
        resultInfo.setCode(300);
        return resultInfo;
    }

}

com.shsxt.model.ResultInfo

public class ResultInfo {
    private Integer code=200;
    private String msg="success";

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值