Skip to content

整理 SpringBoot 知识点(一)

Published: at 06:18

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;
}

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如下:

idnameagegenderphone
1小坤19118800000001
2小徐18118800000002
3小菜17118800000003
4小蔡16218800000004
5小鸡15118800000005
6小美14118800000006

接下来,我们要新建一个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);
}

再然后,在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);
    }

}

随后,运行项目,在浏览器中输入http://localhost:8080/selectUserById?id=1,查看效果,发现浏览器中输出:

{"id":1,"name":"小坤","age":19,"gender":1,"phone":"18800000001"}

上一篇文章
整理 SpringBoot 知识点(二)
下一篇文章
测试 latex 是否可以正常渲染