在Spring Boot应用程序中,最好将所有配置保留在application.properties文件中。我们可以根据环境拥有多个application.properties文件。以下是基于环境的应用程序属性文件的示例:
-rw-r--r-- 1 joe staff 922 Dec 4 14:26 application-prod.properties -rw-r--r-- 1 joe staff 930 Dec 4 14:26 application-stage.properties -rw-r--r-- 1 joe staff 879 Dec 4 14:26 application-test.properties -rw-r--r-- 1 joe staff 8439 Dec 4 14:26 application.properties
许多开发人员在Spring Boot中将设置或配置保留在Java代码中。在 java 代码中保留设置或配置不是一个好的做法。
使用@value批注
我们可以使用@Value注释并访问如下属性:
@Value("${arc.target.environment}") private String targetEnvironment;
使用@Autowired环境
我们可以使用@Autowired提供的弹簧将环境注入豆类。
@Autowired private Environment environments; public void getApplicationProperties() { String path = environments.getProperty("arc.target.mode"); }
使用@ConfigurationProperties环境
@ConfigurationProperties可以如下所示来获取应用程序属性。
arc.environments.stage.endpoint.image=api-url-image
@Configuration @ConfigurationProperties(prefix = "arc") @Getter @Setter public class ArcEndpointConfig { private Map environments = new HashMap<>(); @Getter @Setter public static class Endpoint{ private Map endpoint = new HashMap<>(); } }
使用自定义代码
一些情况下不能使用以上方法,这时可以使用如下所示的自定义代码获取应用程序属性。
package com.thecoder.db;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class DBManager {
private static String user;
private static String password;
private static String url;
private static Connection connection;
private DBManager() {
}
public static Connection getConnection() {
// url = "jdbc:mysql://localhost:3306/studentManagement?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
// user = "root";
// password = "root";
try ( InputStream input = DBManager.class.getClassLoader().getResourceAsStream("application.properties")) {
Properties prop = new Properties();
if (input == null) {
System.out.println("Sorry, unable to find application.properties");
}
//load a properties file from class path, inside static method
prop.load(input);
//get the property value and print it out
//System.out.println(prop.getProperty("url"));
url = prop.getProperty("spring.datasource.url");
//System.out.println(prop.getProperty("user"));
user = prop.getProperty("spring.datasource.username");
//System.out.println(prop.getProperty("password"));
password = prop.getProperty("spring.datasource.password");
} catch (IOException ex) {
ex.printStackTrace();
}
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return connection;
}
}