SpringBoot

目录

 

【*】什么是SpringBoot

【*】SpringBoot特点

【*】SpringBoot常用的启动器

【*】添加引导类

【*】SpringBoot热部署

【*】引导类@SpringBootApplication包含的三个重要的注解

【*】SpringBoot的配置文件

【*】配置文件和配置类属性的映射

【*】常用注解

【*】属性读取类

【*】使用属性类(3种方式)

【*】拦截器

【*】SpringBoot Junit测试

【*】实体类

【*】SpringBoot访问静态资源


【*】什么是SpringBoot

  • SpringBoot是Spring项目中的一个子工程

  • 帮我们快速的构建庞大的spring项目

  • 并且尽可能的减少一切xml配置

  • 项目依赖管理比较方便(都是启动器)

  • 能够有效的避免技术版本冲突的问题

  • 让我们关注于业务而非配置

【*】SpringBoot特点

  • 内置tomcat(可以直接打包成jar包)
  • 基本不需要xml配置
  • 使用starter启动器,避免版本冲突
  • 配置简单

【*】SpringBoot常用的启动器

  • web启动器:spring-boot-starter-web
  • mybatis启动器:mybatis-spring-boot-starter
  • 通用mapper:mapper-spring-boot-starter
  • themeleaf 模板:spring-boot-starter-thymeleaf

【*】添加引导类

  • @SpringBootApplication:使用该注解代表这是SpringBoot的引导类
  • SpringApplication.run(MySpringBootApplication.class):可以启动SpringBoot项目

【*】SpringBoot热部署

<!--热部署配置-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
</dependency>

【*】引导类@SpringBootApplication包含的三个重要的注解

  • @SpringBootConfiguration

声明当前类是SpringBoot应用的配置类,项目中只能有一个,在启动类上

  • @EnableAutoConfiguration(帮助我们完成默认配置)

开启自动配置,告诉SpringBoot基于所添加的依赖,去“猜测”你想要如何配置Spring。比如我们引入了spring-boot-starter-web,而这个启动器中帮我们添加了tomcat、SpringMVC的依赖,此时自动配置就知道你是要开发一个web应用,所以就帮你完成了web及SpringMVC的默认配置了!

  • @ComponentScan

扫描的包,例如我们在类上加了@bean,在项目启动的时候就会将我们的bean实例注入Spring容器,例如启动的时候加载过滤器

【*】SpringBoot的配置文件

  • SpringBoot默认会从Resources目录下加载application.yml
  • application.yml里面的属性是 key: value 键值的存储关系

【*】配置文件和配置类属性的映射

1.第一种方式使用@Value,不需要对映射的属性提供set方法

  • 属性文件
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/lby
jdbc.username=root
jdbc.password=123
  • 需要映射属性的类 
@Configuration
@PropertySource("classpath:jdbc.properties")
public class JdbcConfiguration {

    @Value("${jdbc.url}")
    String url;
    @Value("${jdbc.driverClassName}")
    String driverClassName;
    @Value("${jdbc.username}")
    String username;
    @Value("${jdbc.password}")
    String password;

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
}
  • @Configuration:声明JdbcConfiguration是一个配置类。

  • @PropertySource:指定属性文件的路径是:classpath:jdbc.properties

  • 如果映射的属性在Resource下的application.yml中则不需要@PropertySource

  • 通过@Value为属性注入值,可以将属性文件的内容注入到对应声明该注解的属性当中,可以获取配置文件的内容

  • 通过@Bean将 dataSource()方法声明为一个注册Bean的方法,Spring会自动调用该方法,将方法的返回值加入Spring容器中。相当于以前的bean标签

  • 然后就可以在任意位置通过@Autowired注入DataSource了!

2.不使用@Value,使用属性类

@ConfigurationProperties(prefix = "jdbc")
public class JdbcProperties {
    private String url;
    private String driverClassName;
    private String username;
    private String password;

    public String getUrl() {
        return url;
    }

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

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    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;
    }
}
  • 在类上通过@ConfigurationProperties注解声明当前类为属性读取类

  • prefix="jdbc"读取属性文件(以.properties结尾的文件)中,前缀为jdbc的值。注意不是属性文件而是属性文件中以jdbc为前缀的值

  • 在类上定义各个属性,名称必须与属性文件中jdbc.后面部分一致,并且必须具有getter和setter方法,例如属性文件中的值是jdbc.url,那么在类中对应的属性就应该是url

  • 需要注意的是,这里我们并没有指定属性文件的地址,SpringBoot默认会读取文件名为application.properties的资源文件

@Controller
@ConfigurationProperties(prefix = "person")
public class QuickStartController {

    private String name;
    private Integer age;

    @RequestMapping("/quick")
    @ResponseBody
    public String quick(){
        return "springboot 访问成功! name="+name+",age="+age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

【*】使用属性类(3种方式)

  • 通过@EnableConfigurationProperties(JdbcProperties.class)来声明要使用JdbcProperties这个类的对象

  • 然后你可以通过以下方式在JdbcConfiguration类中注入JdbcProperties:

1.@Autowired注入

@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfiguration {

    @Autowired
    private JdbcProperties jdbcProperties;

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(jdbcProperties.getUrl());
        dataSource.setDriverClassName(jdbcProperties.getDriverClassName());
        dataSource.setUsername(jdbcProperties.getUsername());
        dataSource.setPassword(jdbcProperties.getPassword());
        return dataSource;
    }

}

2.构造函数注入

@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfiguration {

    private JdbcProperties jdbcProperties;

    public JdbcConfiguration(JdbcProperties jdbcProperties){
        this.jdbcProperties = jdbcProperties;
    }

    @Bean
    public DataSource dataSource() {
        // 略
    }

}

3.@Bean方法的参数注入

@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfiguration {

    @Bean
    public DataSource dataSource(JdbcProperties jdbcProperties) {
        // ...
    }
}

4.更加优雅的注入方式(不使用属性类的方式),将@ConfigurationProperties(prefix = "jdbc")添加在方法上

  • 被注入属性的类需要有对应属性的set方法,也就是 jdbc.url 对应类中的属性为 url ,这个类又要 url 属性的set方法
  • @ConfigurationProperties(prefix = "jdbc")声明在需要使用的@Bean的方法上,然后SpringBoot就会自动调用这个Bean(此处是DataSource)的set方法,然后完成注入。
@Configuration
public class JdbcConfiguration {
    
    @Bean
    // 声明要注入的属性前缀,SpringBoot会自动把相关属性通过set方法注入到DataSource中
    @ConfigurationProperties(prefix = "jdbc")
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        return dataSource;
    }
}

【*】常用注解

@RestController
public class HelloController {

    @Autowired
    private DataSource dataSource;

    @GetMapping("show")
    public String test(){
        return "hello Spring Boot!";
    }

}
  • @RestController:代表当前类是控制层,视图解析器不起作用,方法的返回值是什么,就返回什么内容
  • @Controller:代表当前类是控制层,其中方法的返回结果默认是一个界面
  • @Autowired:自动注入,会将声明了该注解对象注入到当前的类,无需去实例化
  • @RequestMapping("show"):映射请求路径
  • @GetMapping("show") = @RequestMapping(method = RequestMethod.GET) ,用于GET请求,查询
  • @postMapping = @RequestMapping(method = RequestMethod.POST),用于POST请求,上传

【*】拦截器

1.自定义拦截器

  • 实现HandlerInterceptor接口
  • 重写preHandle、postHandle、afterCompletion方法
@Component
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle method is running!");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle method is running!");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion method is running!");
    }
}

2.注入拦截器

  • 实现WebMvcConfigurer
  • 注入自定义拦截器
  • 配置拦截的请求

然后定义配置类,注册拦截器(拦截器拦截的是请求,所以应该在mvc处理请求url时进行拦截):

@Configuration
public class MvcConfiguration implements WebMvcConfigurer {

    @Autowired
    private HandlerInterceptor myInterceptor;

    /**
     * 重写接口中的addInterceptors方法,添加自定义拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor).addPathPatterns("/**");
    }
}

preHandle、postHandle与afterCompletion

  • preHandle

调用时间:Controller方法处理之前

执行顺序:链式Intercepter情况下,Intercepter按照声明的顺序一个接一个执行

若返回false,则中断执行,注意:不会进入afterCompletion

  • postHandle

调用前提:preHandle返回true

调用时间:Controller方法处理完之后,DispatcherServlet进行视图的渲染之前,也就是说在这个方法中你可以对ModelAndView进行操作

执行顺序:链式Intercepter情况下,Intercepter按照声明的顺序倒着执行

备注:postHandle虽然post打头,但post、get方法都能处理

  • afterCompletion

调用前提:preHandle返回true

调用时间:DispatcherServlet进行视图的渲染之后

多用于清理资源

【*】SpringBoot Junit测试

  • 在测试类需要添加两个注解
    • @RunWith(SpringRunner.class)
    • @SpringBootTest(classes = MySpringBootApplication.class)
  • 在测试方法上添加@Test注解
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MySpringBootApplication.class)
public class MapperTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void test() {
        List<User> users = userMapper.queryUserList();
        System.out.println(users);
    }

}

【*】实体类

@Entity
public class User {
    // 主键
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    // 用户名
    private String username;
    // 密码
    private String password;
    // 姓名
    private String name;
 
    //此处省略setter和getter方法... ...
}

【*】SpringBoot访问静态资源

  • classpath:/META-INF/resources/

  • classpath:/resources/

  • classpath:/static/

  • classpath:/public/

【*】SpringBoot默认的数据源HikariCP

【*】SpringBoot使用@ConfigurationProperties(prefix = "person")读取yml的属性,向实体的参数中注入值

  • 导入dependency
<!-- 导入配置文件处理器,配置文件进行绑定就会有提示,需要重启 -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-configuration-processor</artifactId>
  <optional>true</optional>
</dependency>
  • 编写Person实体
@Component //注册bean到容器中
public class Person {
    private String name;
    private Integer age;
    private Boolean happy;
    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;
    
    //有参无参构造、get、set方法、toString()方法  
}
  • 编写yml配置
person:
  name: qinjiang
  age: 3
  happy: false
  birth: 2000/01/01
  maps: {k1: v1,k2: v2}
  lists:
   - code
   - girl
   - music
  dog:
    name: 旺财
    age: 1
  • 将yml配置的值注入到Person

/*
@ConfigurationProperties作用:
将配置文件中配置的每一个属性的值,映射到这个组件中;
告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定
参数 prefix = “person” : 将配置文件中的person下面的所有属性一一对应
*/
@Component //注册bean
@ConfigurationProperties(prefix = "person")
public class Person {
    private String name;
    private Integer age;
    private Boolean happy;
    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SuperLBY

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值