SpringBoot工具类读取配置文件,静态变量从配置文件读取

avatar 2020年6月3日22:33:08 评论 199 views

刚才帮一个朋友解决了一个很简单的问题,相信很多朋友可能会遇到。

关于Java类读取 application.yml 配置文件里的值的问题。

目前我所了解的主要是三种方式:

① @Value("${xxxx}")

② ConfigurationProperties 配置

③ 通过 Enviroment 获取

今天我们这里只介绍第三种

该同学的需求是在 JdbcUtil 里获取 application.yml 里的数据源信息(url,账号和密码)

解决代码如下

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.sql.*;

@Component
public class JdbcUtil {

    private static String url = "";
    private static String username = "";
    private static String password = "";

    @Autowired
    private Environment env;

    @PostConstruct
    public void config() {
        url = env.getProperty("spring.datasource.url");
        username = env.getProperty("spring.datasource.username");
        password = env.getProperty("spring.datasource.password");
    }

    public static Connection getConnection() throws SQLException {
        System.out.println("url="+url+",username="+username+",password="+password);
        return DriverManager.getConnection(url, username, password);
    }

    public static void close(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void executeQuery(String sql) throws SQLException {
        Connection conn = getConnection();
        PreparedStatement ptmt = conn.prepareStatement(sql);
        ResultSet rs = ptmt.executeQuery();
        while (rs.next()) {
            System.out.println(rs);
        }
    }


    public static String getUrl() {
        return url;
    }

    public static void setUrl(String url) {
        JdbcUtil.url = url;
    }

    public static String getUsername() {
        return username;
    }

    public static void setUsername(String username) {
        JdbcUtil.username = username;
    }

    public static String getPassword() {
        return password;
    }

    public static void setPassword(String password) {
        JdbcUtil.password = password;
    }
}

 

重点在

@Autowired
private Environment env;

@PostConstruct
public void config() {
    url = env.getProperty("spring.datasource.url");
    username = env.getProperty("spring.datasource.username");
    password = env.getProperty("spring.datasource.password");
}

 

  • 微信
  • 交流学习,有偿服务
  • weinxin
  • 博客/Java交流群
  • 资源分享,问题解决,技术交流。群号:590480292
  • weinxin
avatar

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: