注解@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 @   阿风小子  阅读(158)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示