SpringBoot 中 yml 的配置与获取
在application.yml
文件中,自定义配置可以如下所示:
student:
name: 小坤
age: 18
hobbies:
- 唱
- 跳
- rap
- 篮球
- 注意:层次之间缩进要对齐,并且冒号后面一定要空格后再写入值,如果是数组,则换行后每一行是一个值,前面加上
-
,并且-
后面也要加上一个空格。
获取配置方法1:使用@Value("${属性}")
,在pojo
实体类中的运用如下:
@Data
@NoArgsConstructor
@Component
public class Student {
@Value("${student.name}")
private String name;
@Value("${student.age}")
private Integer age;
}
获取配置方法2:使用@ConfigurationProperties(prefix = "前缀")
,在pojo
实体类中的运用如下:
@Data
@NoArgsConstructor
@Component
@ConfigurationProperties(prefix = "student")
public class Student {
private String name;
private Integer age;
private List<String> hobbies;
}
- 注意:倘若使用方法2,则
pojo
实体类中的属性名称必须和yml
配置文件中的名称一模一样。 - 注意:
@Value
仅支持简单的字符串解析,不能解析List
这种复杂的数据结构。
SpringBoot 整合 MyBatis
MyBatis的起步依赖如下,将其加入到pom.xml
中:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
同时也要引入MySQL的驱动依赖,如下:
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
在配置文件application.yml
中写入数据源配置,格式如下:
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/{数据库名}
username: {用户名}
password: {密码}
假如我们现在有一个数据库名字叫做mybatis
,并且其中有一张表user
如下:
id | name | age | gender | phone |
---|---|---|---|---|
1 | 小坤 | 19 | 1 | 18800000001 |
2 | 小徐 | 18 | 1 | 18800000002 |
3 | 小菜 | 17 | 1 | 18800000003 |
4 | 小蔡 | 16 | 2 | 18800000004 |
5 | 小鸡 | 15 | 1 | 18800000005 |
6 | 小美 | 14 | 1 | 18800000006 |
接下来,我们要新建一个pojo
实体类User
,代码如下:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String name;
private Short age;
private Integer gender;
private String phone;
}
然后在mapper
包下新建接口UserMapper
,如下:
@Mapper
public interface UserMapper {
@Select("select * from user where id = #{id}")
public User selectUserById(Integer id);
}
- 注意:一定不要忘记加
@Mapper
。
再然后,在service
包下新建接口UserService
,如下:
public interface UserService {
public User selectUserById(Integer id);
}
紧接着,在service
包的impl
包下,新建实现类UserServiceImpl
,实现UserService
接口,并加入@Service
注解交给IOC
容器处理:
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User selectUserById(Integer id) {
return userMapper.selectUserById(id);
}
}
最后,在controller
包下新建UserController
,代码如下:
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/selectUserById")
public User selectUserById(Integer id) {
return userService.selectUserById(id);
}
}
- 注意:上述操作属于MVC架构。
随后,运行项目,在浏览器中输入http://localhost:8080/selectUserById?id=1
,查看效果,发现浏览器中输出:
{"id":1,"name":"小坤","age":19,"gender":1,"phone":"18800000001"}