Springboot

一、Spring Boot的第一个程序

  1. 创建一个SpringBoot项目
  2. 创建Controller类
  3. 在类名前加@RestController
  4. 在方法前加@GetMapping("")
  5. 运行Application

二、配置文件的使用(#注释)

1、配置文件的类型以及区别

application.properties(优先加载)

  • 更改端口:server.port = 8888

  • 修改上下文:server.servlet.context-path=/my

application.yml

  • 更改端口:server:

​ port:8888

  • 改上下文 servlet:

​ context-path:/my

2、多环境配置

  • 命名方式:application-dev.properties,application-online.properties,application-test.properties
  • 激活方式:在主配置文件使用spring.profiles.active=dev/online/test

3、自定义配置

  1. 乱码解决方式(File>Settings>Editor>File Encodings 选择UTF-8并Transparent打√):

    spring.http.encoding.charset=UTF-8
    spring.http.encoding.enabled=true
    spring.http.encoding.force=true

  2. 自定义类赋值:

    • application.properties中

      student.uId=1
      student.uName=奥奥
      student.uAge=10

    • application.yml中

      student:

      uId: 1

      uName: 奥奥

      uAge: 10

  3. 读取自定义配置的值

    @Value("${student.uId}")

    private int uId;

  4. 类中加载自定义配置文件:

    @Component

    @PropertySource(value = “classpath:school.properties”)//指定外部配置文件yml不支持

    @ConfigurationProperties(prefix = “school”)//前缀,对应的是配置文件中的school

    在Controller中使用获取:

    @Autowired
    private Student student;

三、Spring Boot 集成mybatis环境

1、创建mybatis项目

  • 选择起步依赖

    Developer Tools > Sptring Boot DevTools(热部署)/ Lombok

    Web > Spring Web

    SQL > Mybatis Framework / MySQL Driver

  • 调用数据库连接池(copy到pom.xml)

    <!-- alibaba的druid数据库连接池 -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid-spring-boot-starter</artifactId>
                <version>1.1.20</version>
            </dependency>
    

2、Spring Boot 集成mybatis代码编写

  1. 创建数据源

    • application.properties

      spring.datasource.username=root
      spring.datasource.password=
      spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
      spring.datasource.url=jdbc:mysql://localhost:3306/student?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
      spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
      
      #指定Bean的位置
      #指定mapper文件的位置
      mybatis.type-aliases-package=com.ao.pojo
      mybatis.mapper-locations=classpath:mapper/*.xml
      
    • application.yml

      spring:
        datasource:
          username: 
          password: 
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:jdbc:mysql://localhost:3306/student?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
          type: com.alibaba.druid.pool.DruidDataSource
          
      #指定Bean的位置
      #指定mapper文件的位置
      mybatis:
        type-aliases-package: com.ao.pojo                    
        mapper-locations: classpath:mapper/*.xml             
      
  2. 编写Dao层

    • 在Mapper Package 创建 mapper接口并加上@Mapper//spring boot会扫描该注解

      可去掉@Mapper在启动类Application加上@MapperScan(“com.ao.dao”)

    • 在resources下创建mapper文件夹,并创建与Dao层mapper接口名相同的xml文件

    • <?xml version="1.0" encoding="UTF-8" ?>
      <!DOCTYPE mapper
              PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
              "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
      <mapper namespace="com.ao.dao.StudentMapper">
          <!--查询多条数据-->
          <select id="selectAllStudent" resultType="student">
              SELECT id,name,age,score FROM t_student
          </select>
      </mapper>
      
  3. 实现service层

    • 创建service package 并创建接口

    • 创建serviceImpl package 实现service接口

    • 在serviceImpl中(studentMapper)报错按Alt+Enter

    • 在启动类Application加入@EnableTransactionManagement //开启事务支持 并在此处开启

      @Service
      @Transactional//开启事务
      public class StudentServiceImpl implements StudentService {
      
          //注入dao
          @Autowired
          private StudentMapper studentMapper;
      
          @Override
          public List<Student> selectAllStudent() {
              return studentMapper.selectAllStudent();
          }
      }
      
  4. 实现controller层

    @RestController
    public class StudentController {
    
        //注入service
        @Autowired
        private StudentService studentService;
    
        @GetMapping("select")
        public List<Student> selectStudent() {
            return studentService.selectAllStudent();
        }
    }
    
  5. 扫描dao层的xml:在pom里的里添加

         <resources>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>true</filtering>
                </resource>
            </resources>
    
  6. 解决前端返回实体类驼峰命名与下划线的问题加入注解进行映射

    @JsonProperty(value="name") 
    
  7. 解决前端返回变量名字不匹配问题

    @PathVariable("id")
    

四、Spring Boot lombok(选用)

  • 导入可省去实体类的Getter、Setter、toString、equals()、hashCode()方法

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    
  • 需要安装插件否则会报错Settings>Plugins>搜索Lombok并下载

  • 在实体类上加上@Data注解

五、Spring Boot 配置拦截器和过滤器

1、配置拦截器

  • 在interceptor package 中创建自定义拦截器MyInterceptor类 实现 HandlerInterceptor 接口并重写 preHandle方法

    public class MyInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            System.out.println("拦截器");
            return true;
        }
    }
    
  • 创建注册拦截器InterceptorConfig类 实现 WebMvcConfigurer 接口并重写 addInterceptors方法

  • 方法一

    1. @Configuration //或者@Component
      public class InterceptorConfig implements WebMvcConfigurer {
          /*
          注册拦截器
           */ 
          @Override
          public void addInterceptors(InterceptorRegistry registry) { 
          
              //将拦截器对象传入到方法中完成注册
              InterceptorRegistration r1 = registry.addInterceptor(new MyInterceptor()); 
      
              //配置拦截器请求
              r1.addPathPatterns("/*");
      
              //配置不拦截的请求
              r1.excludePathPatterns("/qk");
          }
      }
      
    2. 方法二 :需要在MyInterceptor上加入@Component或者@Configuration注解

      @Configuration //或者@Component
      public class InterceptorConfig implements WebMvcConfigurer {
          /*
          注册拦截器
           */
          @Autowired
          private MyInterceptor myInterceptor;
          @Override
          public void addInterceptors(InterceptorRegistry registry) {
          
              //将拦截器对象传入到方法中完成注册 
              InterceptorRegistration r1 = registry.addInterceptor(myInterceptor);
              
              //配置拦截器请求
              r1.addPathPatterns("/*");
              
              //配置不拦截的请求
              r1.excludePathPatterns("/qk");
          }
      }
      
      
    3. 方法三

      @Configuration //或者@Component
      public class InterceptorConfig implements WebMvcConfigurer {
          /*
          注册拦截器
           */
          @Override
          public void addInterceptors(InterceptorRegistry registry) {
      
              //将拦截器对象传入到方法中完成注册 
              InterceptorRegistration r1 = registry.addInterceptor(getMyInterceptor());
      
              //配置拦截器请求
              r1.addPathPatterns("/*");
      
              //配置不拦截的请求
              r1.excludePathPatterns("/qk");
          }
          @Bean//会将该对象放入到spring容器中
          public MyInterceptor getMyInterceptor(){
              return new MyInterceptor();
          }
      }
      

2、配置过滤器

  • 在filter package 中创建自定义拦截器MyFilter(javax.servlet.*)类 实现 Filter接口并重写

    init()、destroy()、doFilter()方法

  • 在doFilter中调用doFilter()并在类上使用@WebFilter("/*") //JavaEE中的

    package com.ao.filter; 
    
    import javax.servlet.*;
    import javax.servlet.FilterConfig;
    import javax.servlet.annotation.WebFilter;
    import java.io.IOException;
    
    @WebFilter("/*")//JavaEE中的
    public class MyFilter implements Filter {
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
        }
        @Override
        public void destroy() {
        }
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            System.out.println("拦截器");
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }
    
  • 在Application中配置@ServletComponentScan(basePackages = {“com.ao.filter”})扫描filter包

  • 创建过滤器配置类FilterConfig加上@Configuration //或者@Component

    @Configuration
    public class FilterConfig {
    
        @Bean
        public FilterRegistrationBean myFilter(){
            FilterRegistrationBean frb1 = new FilterRegistrationBean(new MyFilter());
            //设置过滤请求
            frb1.addUrlPatterns("/*");
    
            return frb1;
        }
    }
    

3、servlet的使用

  1. 继承HttpServlet重写方法

  2. 在Application中配置扫描servlet包

    @ServletComponentScan(basePackages = {"com.ao.servlet"})
    

六、使用actuator监控Spring Boot

  1. 创建项目时添加actuator起步依赖

  2. 配置文件

    #actuator端口号使用:http://localhost:8081/actuator访问
    management.server.port=8081
    
    #开启所有监控
    management.endpoints.web.exposure.include=*
    
    #添加info信息使用:http://localhost:8081/actuator/info访问
    info.author=monkey1024
    info.url=www.monkey1024.com
    info.age=18
    
  3. 图形化界面

    <properties>
            <java.version>1.8</java.version>
            <spring-boot-admin.version>2.3.1</spring-boot-admin.version>
    </properties>
    <dependencys>
        <!--spring boot admin依赖-->
        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-client</artifactId>
        </dependency>
    </dependencys>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>de.codecentric</groupId>
                <artifactId>spring-boot-admin-dependencies</artifactId>
                <version>${spring-boot-admin.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    
  4. 创建一个actuatorserver模块(Spring Boot Admin 在项目或者模块创建在Ops下选择起步依赖)

    • 没导入actuator和spring boot admin起步依赖请复制

      <properties>
              <java.version>1.8</java.version>
              <spring-boot-admin.version>2.3.1</spring-boot-admin.version>
      </properties>
      <dependencys>
          <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-actuator</artifactId>
          </dependency>
          <!--spring boot admin相关依赖-->
          <dependency>
              <groupId>de.codecentric</groupId>
              <artifactId>spring-boot-admin-starter-server</artifactId>
          </dependency> 
      </dependencies>
      <dependencyManagement>
              <dependencies>
                  <dependency>
                      <groupId>de.codecentric</groupId>
                      <artifactId>spring-boot-admin-dependencies</artifactId>
                      <version>${spring-boot-admin.version}</version>
                      <type>pom</type>
                      <scope>import</scope>
                  </dependency>
              </dependencies>
      </dependencyManagement>
      
    • 在Application中使用@EnableAdminServer //开启AdminServer

    • 在配置文件中

      #配置端口号
      server.port=8082
      
  5. 在被监控的模块的配置文件中使用并启动被监控的Application类

    #配置spring boot admin地址
    spring.boot.admin.client.url=http://localhost:8082/
    

七、Spring Boot自动配置原理

  • 在spring boot 中的@EnableAutoConfiguration就是开启自动配置

  • 自动配置的实现步骤:

    1. spring boot会根据开发者添加的依赖判断是否使用了某个技术,比如在依赖中有DispatcherServlet,那就说明使用了spring mvc技术。
    2. spring boot判断出开发者所使用的技术之后,会从自动配置(AutoConfigure)相关的包下找到该技术相关的配置类。
    3. spring boot会加载这些配置类,如果配置文件有写相关的配置信息的话会将该信息读取到配置类的对象中,然后加载到spring容器中,这样就完成了自动配置了。
  • 如果AutoConfigure包下没有配置类,需要手动配置

    配置类和自动配置类的命名规范:

    ​ 配置类:*Properties

    ​ 自动配置类:*AutoConfiguration

  • 在配置类里添加debug=true

    这样就开启了spring boot的debug模式,在启动spring boot的时候可以在控制台中看到目前已经加载的配置类。

八、自定义起步依赖

  1. 创建maven或spring boot 模块

  2. Parent选择none,输入GroupId和ArtifactId命名规范:*-spring-boot-starter

  3. 在pom配置文件中的依赖添加jar

    <groupId>com.admin</groupId>
    <artifactId>06admin-spring-boot-starter</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    
  4. 创建spring boot模块ArtifactId命名规范:*-spring-boot-autoconfiguer 起步依赖不勾选

  5. 打开创建好的spring boot(07admin-spring-boot-autoconfiguer)模块中的pom文件拷贝

    <groupId>com.ao</groupId>
    <artifactId>07admin-spring-boot-autoconfiguer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    

    拷贝到*-spring-boot-starter模块的pom中

    <!-- 自动配置依赖-->
        <dependencies>
            <dependency>
                <groupId>com.ao</groupId>
                <artifactId>07admin-spring-boot-autoconfiguer</artifactId>
                <version>0.0.1-SNAPSHOT</version>
            </dependency>
        </dependencies>
    
  6. 在创建好的spring boot(07admin-spring-boot-autoconfiguer)模块的pom文件中添加

        <dependencies>
            <!--为properties类生成相应的json文件-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-configuration-processor</artifactId>
                <optional>true</optional>
            </dependency>
            .
            .
            .
        </dependencies>
    
    • 删掉Application.class并创建UserProperties.class

      /**
       * 用户配置类
       */
      @ConfigurationProperties(prefix = "ao.user")
      public class UserProperties {
          private String userName;
          private String password;
      
          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;
          }
      }
      
    • 创建UserService类

      /**
       * 假设这个事spring boot 中的第三方技术
       */
      public class UserService {
          private UserProperties userProperties;
      
          public UserService(UserProperties userProperties) {
              this.userProperties = userProperties;
          }
      
          public UserService() {
          }
          public boolean admin(){
              if ("admin".equals(userProperties.getUserName())&&"123".equals(userProperties.getPassword())){
                  return true;
              }
              return false;
          }
      
    • 创建UserAutoConfiguration类

      /**
       *用户自动配置类
       */
      @Configuration
      @ConditionalOnWebApplication//在web下使用
      @EnableConfigurationProperties(UserProperties.class)
      public class UserAutoConfiguration {
      
          @Autowired
          private UserProperties userProperties;
          /*
          将UserService对象放入spring容器中
           */
          @Bean//把自己new的Spring对象放到Spring容器中
          @ConditionalOnMissingBean(UserService.class)//当容器不存在该对象时执行此方法
          public UserService addUserService(){
              return new UserService(userProperties);
          }
      }
      
    • 在maven中选择要编译的模块Lifecycle>compile

  7. 创建spring boot 模块导入自定义依赖创建controller类

    @RestController
    public class UserController {
    
        @Autowired
        private UserService userService;
    
        @GetMapping("admin")
        public String admin(){
            boolean flag = userService.admin();
            return flag+"";
        }
    }
    
  8. admin和password可在配置文件中赋值

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值