gpt4 book ai didi

java - 带数据源的 Spring 配置属性 (YML)

转载 作者:行者123 更新时间:2023-12-02 01:54:12 28 4
gpt4 key购买 nike

我需要在我的 jar 之外使用配置属性。为此,我使用一个类来配置:

@Data
@Configuration
@PropertySource(value={"file:///C:/main.properties"})
public class YAMLConfig {

@Bean
@ConfigurationProperties(prefix = "datasource.db-prod")
public DataSource personDataSource() {
return DataSourceBuilder.create().build();
}

private String name;
private String environment;
private String datasource;
private List<String> servers = new ArrayList<>();

// standard getters and setters

当我在程序中使用时,我的 main.properties 工作得很好。但我希望这个在外面,因为我想在我想要的时候改变。

我的 Spring 类(class):

@SpringBootApplication
@EnableEncryptableProperties
public class PsuInfoToolApplication {

@Autowired
private static YAMLConfig config;

public static void main(String[] args) {
SpringApplication.run(PsuInfoToolApplication.class, args);

}

但是它不起作用,似乎该文件没有配置数据源:java.sql.SQLException: url 不能为空

我该怎么办?我想在 jar 外部创建一个配置文件,并使用 DataSource 对象直接配置我的数据库。

最佳答案

Load the file from the classpath

您可以从类路径加载属性文件,以便在运行时自动拾取该文件。

示例代码:

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class MyPropWithinClasspath {

private Properties prop = null;

public MyPropWithinClasspath(){

InputStream is = null;
try {
this.prop = new Properties();
is = this.getClass().getResourceAsStream("/sample.properties");
prop.load(is);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public String getPropertyValue(String key){
return this.prop.getProperty(key);
}

public static void main(String a[]){

MyPropWithinClasspath mpc = new MyPropWithinClasspath();
System.out.println("db.host: "+mpc.getPropertyValue("db.host"));
System.out.println("db.user: "+mpc.getPropertyValue("db.user"));
System.out.println("db.password: "+mpc.getPropertyValue("db.password"));
}
}

Load the file from environment variable

String extDir = System.getenv(EXTERNAL_DIR);

您可以在external.dir中指定文件的路径。所以java会自动识别该变量。这样您就可以使用环境变量中的路径并加载文件

关于java - 带数据源的 Spring 配置属性 (YML),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52551472/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com