注解@ConfigurationProperties使用方法

注解@ConfigurationProperties使用方法

1、配置文件内容

spring.datasource.url=jdbc:mysql://localhost:3306/satellite_resource?characterEncoding=utf8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

2、创建类

package com.example.demo.user;


import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@ConfigurationProperties(prefix = "spring.datasource")
@Component
@Data
public class DatasourcePro {

    private String url;

    private String username;

    private String password;

    // 配置文件中是driver-class-name, 转驼峰命名便可以绑定成
    private String driverClassName;


}

3、用法

package com.example.demo.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/config")
public class ConfigurationPropertiesController {

    @Autowired
    private DatasourcePro datasourcePro;

    @GetMapping("/test")
    public Map<String, Object> test() {

        Map<String, Object> map = new HashMap<>();
        map.put("url", datasourcePro.getUrl());
        map.put("userName", datasourcePro.getUsername());
        map.put("password", datasourcePro.getPassword());
        map.put("className", datasourcePro.getDriverClassName());

        return map;
    }
}

4、结果

访问:http://localhost:9110/config/test

{
"password": "123456",
"className": "com.mysql.cj.jdbc.Driver",
"userName": "root",
"url": "jdbc:mysql://localhost:3306/satellite_resource?characterEncoding=utf8&serverTimezone=Asia/Shanghai"
}

 

posted @ 2021-12-24 10:21  袁骞骞  阅读(374)  评论(0编辑  收藏  举报