How to inject environmental variables inside spring xml configuration?

后端 未结 3 1053
借酒劲吻你
借酒劲吻你 2021-01-30 21:50

AWS talks about System.getProperty(\"JDBC_CONNECTION_STRING\") in http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_Java.managing.html after we s

3条回答
  •  抹茶落季
    2021-01-30 22:38

    For someone who use JavaConfig:

    In @Configuration file we need to have:

    @Bean 
    public static PropertyPlaceholderConfigurer properties() {
    
        PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
        ClassPathResource[] resources = new ClassPathResource[ ] {
            new ClassPathResource("db.properties")
        };
        ppc.setLocations( resources );
        ppc.setIgnoreUnresolvablePlaceholders( true );
        ppc.setSearchSystemEnvironment(true);
        return ppc;
    }
    
    @Value("${db.url}")
    private String dbUrl; 
    @Value("${db.driver}")
    private String dbDriver;
    @Value("${db.username}")
    private String dbUsername;
    @Value("${db.password}")
    private String dbPassword;
    
    @Bean
    public DataSource db() {
    
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setUrl(dbUrl);
        dataSource.setDriverClassName(dbDriver);
        dataSource.setUsername(dbUsername);
        dataSource.setPassword(dbPassword);
        return dataSource;
    }
    

    important is line: ppc.setSearchSystemEnvironment(true);

    after that in db.properties, I have:

    db.url = ${PG_URL}
    db.driver = ${PG_DRIVER}
    db.username = ${PG_USERNAME}
    db.password = ${PG_PASSWORD}
    

提交回复
热议问题