使用属性文件

1.导入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

2.编辑配置文件

database.driverName=com.mysql.jdbc.Driver
database.url=jdbc.mysql://localhost:3306/chapter3
database.username=root
database.password=123456

3.使用属性配置

package com.springboot.chapter3.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class DataBaseProperties {

    private String driverName = null;
    private String url = null;
    private String username = null;
    private String password = null;

    public String getDriverName() {
        return driverName;
    }

    @Value("${database.driverName}")
    public void setDriverName(String driverName) {
        System.out.println(driverName);
        this.driverName = driverName;
    }

    public String getUrl() {
        return url;
    }

    @Value("${database.url}")
    public void setUrl(String url) {
        System.out.println(url);
        this.url = url;
    }


    public String getUsername() {
        return username;
    }

    @Value("${database.username}")
    public void setUsername(String username) {
        System.out.println(username);
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    @Value("${database.password}")
    public void setPassword(String password) {
        System.out.println(password);
        this.password = password;
    }
}

4.使用@ConfigurationProperties注解

@ConfigurationProperties中配置的字符串database,将与POJO的属性名称组成属性的全限定名去配置文件里查找,这样就能将对应的属性读入到POJO当中。

package com.springboot.chapter3.pojo;

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

@Component
@ConfigurationProperties("database")
public class DataBaseProperties {

    private String driverName = null;
    private String url = null;
    private String username = null;
    private String password = null;

    public String getDriverName() {
        return driverName;
    }

    public void setDriverName(String driverName) {
        System.out.println(driverName);
        this.driverName = driverName;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        System.out.println(url);
        this.url = url;
    }


    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        System.out.println(username);
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        System.out.println(password);
        this.password = password;
    }
}
posted @ 2020-04-11 17:21  xl4ng  阅读(174)  评论(0编辑  收藏  举报