简体   繁体   中英

Override value in application.properties

I write desktop application which connected with API client and this API forces setting URL value

@Value("${ig.api.domain.URL}")
private String igApiDomainURL;

Setting igApiDomainURL showing above is in AbstractService.class of client api libraries so I can't change it.

I create BeanConfiguration.java which load application.properties where the ig.api.domain.URL was defined.

BeanConfiguration.java looks like this:

@Configuration
@PropertySource("application.properties")
public class BeanConfiguration {

    @Bean
    public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean
    public HttpClient httpClient() {
        return HttpClients.createDefault();
    }
}

... and application.properties contains:

ig.api.domain.URL=https://demo-api.ig.com/gateway/deal

I want change URL address defined in application.properties during riunning application (change the URL address depending on the type of account - DEMO/LIVE).

Any suggestions ?

After a long discussion, what finally worked for this very specific scenario was doing something like this:

Create a property file for each possible profile you want, like:

application-dev.properties
application-prod.properties

Properties content example:

property.i.want=abcd

Set the env before creating the ApplicationContext:

System.setProperty("spring.profiles.active", "dev");
ClassPathXmlApplicationContext  context =
                new ClassPathXmlApplicationContext(new String[] {"spring.xml"});

Then set the property source manually, ie:

@Bean
public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() throws IOException {
    String profile = System.getProperty("spring.profiles.active");
    PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
    Resource resource = new ClassPathResource(String.format("application-%s.properties", profile));
    Properties props = PropertiesLoaderUtils.loadProperties(resource);
    pspc.setProperties(props);
    pspc.setPropertySources();
    return pspc;
}

Definitly not the prettiest solution though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM