SpringBoot配置文件自动映射到属性和实体类(8)

一、配置文件加载

1、Controller中配置并指向文件

@Controller
@PropertySource(value = { "application.properties" })//指定配置文件

2、在变量上打注解并指明配置文件中的key

@Value("${web.upload.filepath}")//获取配置文件中的配置参数
private String filePath;

二、实体类配置文件

 1、添加@Component//文件扫描注解

 2、使用@PropertySource({"classpath:jdbc.properties"}) //指定配置文件的位置

 3、使用@ConfigurationProperties 或者 @ConfigurationProperties(prefix="jdbc")//前缀,设置相关的属性

 4、使用@Autowired//通过IOC对象自动注入

示例-新建实体类如下:

package cn.xiaobing.demo.pojo;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component//文件扫描
@PropertySource({"classpath:jdbc.properties"})
//@ConfigurationProperties
@ConfigurationProperties(prefix="jdbc")//前缀
public class JDBCSettings {

    //@Value("${jdbc.driver}")
    //如果属性命名和配置文件中配置name一致就不需要声明@Value("${jdbc.driver}")
    private String driver;

    private String url;
    
    private String username;
    
    private String password;
    
    public String getDriver() {
        return driver;
    }
    public void setDriver(String driver) {
        this.driver = driver;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getpassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public JDBCSettings(String driver, String url, String username, String password) {
        super();
        this.driver = driver;
        this.url = url;
        this.username = username;
        this.password = password;
    }
    public JDBCSettings() {
        super();
    }
    @Override
    public String toString() {
        return "JDBCSetting [driver=" + driver + ", url=" + url + ", username=" + username + ", password=" + password
                + "]";
    }    
}

jdbc.properties文件配置信息

jdbc.driver=com.MysqL.jdbc.Driver
jdbc.url=jdbc:MysqL://localhost:3306/future?useUnicode=true&characterEncoding=utf-8
jdbc.username=Administrator1
jdbc.password=123456

Controller编码

@RestController
public class GetController {
        @Autowired//通过IOC对象自动注入进来
    private JDBCSettings jdbcSettings;
    
    @GetMapping("/v1/getJdbcProperties")
    public Object getJDBCProperties() {
        return jdbcSettings;
    }
}

启动项目访问:

 

 三、不足之处,后续补充。。。

 

相关文章

连接数据库的方式:第一种方式:ODBC:开放数据库连接是微软...
JDBCRequest 使用VariableNamesmysql:数据库连接池对象var...
 1.JDBCDBC(JavaDataBaseConnectivity):Java数据库连接技术...
1.需要jar包的支持:java.sqljavax.sqlmysql-conneter-java....
1.简介Activiti是一个业务流程管理(BPM)框架,它是覆盖了业务...
1.JDBC体系系统一组规范:接口JDBC接口(API)包括两个层次:...