目录
@ConfigurationProperties(对象注入)
一、SpringBoot 概述
1、SpringBoot 简介
SpringBoot 提供了一种快速使用 Spring 的方式,基于约定优于配置的思想,可以让开发人员不必在配置与逻辑业务之间进行思维的切换,全身心的投入到逻辑业务的代码编写中,从而大大提高了开发的效率,一定程度上缩短了项目周期。
2014 年 4 月,Spring Boot 1.0.0 发布,并作为 Spring 的顶级项目之一。
2.SpringBoot 功能
1. 自动配置
- SpringBoot 的自动配置是一个运行时(更准确地说,是应用程序启动时)的过程,考虑了众多因素,才决定 Spring 配置应该用哪个,不该用哪个。该过程是 SpringBoot 自动完成的。
2.起步依赖(依赖传递)
- 起步依赖本质上是一个 Maven 项目对象模型(Project Object Model,POM),定义了对其他库的传递依赖,这些东西加在一起即支持某项功能。
- 简单的说,起步依赖就是将具备某种功能的坐标打包到一起,并提供一些默认的功能。
3. 辅助功能
- 提供了一些大型项目中常见的非功能性特性,如嵌入式服务器、安全、指标,健康检测、外部配置等。
4、SpringBoot 快速入门
- 搭建 SpringBoot 工程,定义 HelloController.hello() 方法,返回“Hello SpringBoot!”。
步骤:
- 创建 Maven 项目;
- 导入 SpringBoot 起步依赖:
<!--springboot工程需要继承的父工程-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
</parent>
<dependencies>
<!--web开发的起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
- 定义 Controller:
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping("/hello")
public String sayHello() {
return "Hello SpringBoot!";
}
}
- 编写引导类:
controller 类必须是 Application 的所在包的类或者子包的类。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootQuickDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootQuickDemoApplication.class, args);
}
}
- 执行 main 方法,启动测试:
- IDEA 快速构建 SpringBoot 工程:
二、SpringBoot 配置
1、配置文件类型
SpringBoot 是基于约定的,所以很多配置都有默认值,但如果想使用自己的配置替换默认配置的话,就可以使用 application.properties 或者 application.yml(application.yaml)进行配置。
# properties
server.port=8080
# yml
server:
port: 8080
常见配置:
spring:
application:
name: demo
server:
port: 8093
connection-timeout: 18000000
servlet:
session:
timeout: 30m # m(分钟),s(秒),h(小时),不写单位默认毫秒
-
SpringBoot 提供了两种配置文件类型:properteis 和 yml/yaml
-
默认配置文件名称:application.properties(application 名称固定)
-
在同一级目录下优先级为:properties > yml > yaml
2、读取配置内容
代码示例:
-
application.yml 配置文件内容
name: outer_name
person:
name: xiaoming
age: 18
address:
- shenzhen
- shanghai
- beijing
# 配置tomcat启动端口
server:
port: 8082
-
@ConfigurationProperties(对象注入)
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private int age;
private String[] address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String[] getAddress() {
return address;
}
public void setAddress(String[] address) {
this.address = address;
}
}
-
Controller
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
// 方式一:@Value 注入
@Value("${name}")
private String name;
@Value("${person.name}")
private String personName;
@Value("${person.address[0]}")
private String personFirstAddress;
// 方式二:Environment 对象
@Autowired
private Environment env;
// 方式三:@ConfigurationProperties 对象注入
@Autowired
private Person person;
@RequestMapping("/hello")
public String sayHello() {
System.out.println(personName); // xiaoming
System.out.println(personFirstAddress); // shenzhen
System.out.println(env.getProperty("person.name")); // xiaoming
System.out.println(env.getProperty("person.address[0]")); // shenzhen
String[] address = person.getAddress();
for (String add: address) {
System.out.println(add);
}
/*
shenzhen
shanghai
beijing
*/
return "Get successfully!";
}
}
三、SpringBoot 整合其他框架
1.整合 Redis
实现步骤:
搭建 SpringBoot 工程
引入 Redis 起步依赖(可使用 IDEA 快捷搭建与引入)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- 配置 Redis 相关属性(可选)
- 注入 RedisTemplate 模板
- 编写测试方法进行测试
代码示例:
-
测试类
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
@SpringBootTest
class DemoApplicationTest {
@Autowired
private RedisTemplate redisTemplate; // 无配置情况下,默认连接本地redis(localhost:6379)
@Test
void testSet() {
// 存入数据
redisTemplate.boundValueOps("name").set("xiaoming");
}
@Test
void testGet() {
// 取数据
Object name = redisTemplate.boundValueOps("name").get();
System.out.println(name);
}
}
-
(application)添加 Redis 配置
2、整合 Mybatis
实现步骤:
- 搭建 SpringBoot 工程
-
引入 Mybatis 起步依赖、添加 Mysql 驱动
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
-
定义表和实体类
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`password` varchar(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
insert into `t_user`(`id`,`username`,`password`) values (1,'zhangsan','123'),(2,'lisi','234');
注解版:
-
application.yml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql:///world?serverTimeZone=UTC # 默认连接本地3306
username: root
password: admin
-
UserMapper
package com.example.mybatis_demo.mapper;
import com.example.mybatis_demo.domain.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface UserMapper {
@Select("select * from t_user")
public List<User> findAll();
}
-
测试类
import com.example.mybatis_demo.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class MybatisDemoApplicationTests {
@Autowired
UserMapper userMapper;
@Test
void testFindAll() {
userMapper.findAll().forEach(
user -> System.out.println(user)
);
}
}
配置版:
-
UserXmlMapper
package com.example.mybatis_demo.mapper;
import com.example.mybatis_demo.domain.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface UserXmlMapper {
public List<User> findAll();
}
-
application.yml
# datasource spring: datasource: url: jdbc:mysql:///springboot?serverTimezone=UTC username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver # mybatis mybatis: mapper-locations: classpath:mapper/*Mapper.xml # mapper映射文件路径 type-aliases-package: com.itheima.springbootmybatis.domain # config-location: # 指定mybatis的核心配置文件
-
UserMapper.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.example.mybatis_demo.mapper.UserXmlMapper">
<select id="findAll" resultType="user">
select * from t_user
</select>
</mapper>
-
测试类
import com.example.mybatis_demo.mapper.UserXmlMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class MybatisDemoApplicationTests {
@Autowired
UserXmlMapper userMapper;
@Test
void testFindAll() {
userMapper.findAll().forEach(
user -> System.out.println(user)
);
}
}