具有数据源(YML)的Spring配置属性

时间:2018-09-28 08:40:02

标签: java spring configuration datasource

我需要在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可以完美运行。但是我想要这个外面的东西,因为我想在需要时改变。

我的春季班:

@SpringBootApplication
@EnableEncryptableProperties
public class PsuInfoToolApplication {

    @Autowired
    private static YAMLConfig config;

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

    }

但是它不起作用,似乎该文件未配置dataSource: java.sql.SQLException:网址不能为空

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

1 个答案:

答案 0 :(得分:2)

  

从类路径中加载文件

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

示例代码:

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"));
    }
}

OR

  

从环境变量加载文件

String extDir = System.getenv(EXTERNAL_DIR);

您可以在external.dir中指定文件的路径。因此,java将自动识别该变量。这样您可以使用env变量中的路径并可以加载文件

相关问题