1

I am looking for a clean way to load values from properties file using the environment value passed from the command line (maven project). I then plan to use the loaded values in Java cucumber test.

Usage : mvn test -Denvironment=staging (it then loads the values from the staging file i.e. application-staging.properties, etc).

I know spring boot offers profiles, wondering if I can do this use a clean approach using the generic spring framework (annotations).

JavaMan
  • 465
  • 1
  • 6
  • 21
  • 1
    Duplicate of https://stackoverflow.com/questions/32196451/environment-specific-application-properties-file-in-spring-boot-application – racraman Dec 10 '18 at 01:24
  • Isn't that related to Spring Boot? – JavaMan Dec 10 '18 at 01:31
  • Oops, sorry yes it is - my apologies. – racraman Dec 10 '18 at 01:38
  • For straigt Spring, check out the PropertySource annotation - https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/PropertySource.html – racraman Dec 10 '18 at 01:39
  • I've got following code and running using mvn test -Denvironment= dev (i've got a file called dev.properties) but I am getting null when trying to print url. \@Configuration \@PropertySource("classpath:${environment}.properties") public class AppTest { \@Value("${base.url}") private String url; \@Bean public Config getConfig(){ Config config = new Config(); config.setUrl(url); return config; } @Test public void test1() { System.out.println("The URL is : "+ getConfig().getUrl()); } } – JavaMan Dec 10 '18 at 02:04

1 Answers1

0

Thanks @racraman. I am able to get this to work using your suggestion around PropertySource. In order to get different environment working i've used something like :

@PropertySource({"classpath:${env}.properties"}).

Cheers !!!

Daredevil
  • 1,672
  • 3
  • 18
  • 47
JavaMan
  • 465
  • 1
  • 6
  • 21
  • 1
    Great - glad you got it working ! By the way, `@PropertySource` does not resolve `@Value` annotations. Instead, you have to use the `@Autowired` Environment as shown in the Example Usage in the doc. Just below that is a section on using `@Value`, but I've never done that. – racraman Dec 10 '18 at 03:29
  • Thanks @racraman. I've used \@Value to setup a default value and it seems to be working fine. As you've mentioned in your comment I've actually used \@Autowired to work with the populated value. Thanks once again !!! – JavaMan Dec 10 '18 at 03:44