Skip to content

Instantly share code, notes, and snippets.

@leonelag
Created March 15, 2018 19:53
Show Gist options
  • Save leonelag/72fc8240ec2b781b4951609036ca041d to your computer and use it in GitHub Desktop.
Save leonelag/72fc8240ec2b781b4951609036ca041d to your computer and use it in GitHub Desktop.
Force Spring Boot application to use a config file.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
public class Main {
private static final String CONFIG_NAME = "myapp"; // FIXME - this will read configs from file myapp.properties; fix as required
private static final Class<?> mainClass = Main.class; // FIXME - adapt to the class containing method main(String[]) in your app.
public static void main(String[] args) {
/*
* Ugly hack.
* Ideally, this config should be found in the env variable, SPRING_CONFIG_NAME.
* However, I'm having a lot of trouble to get env vars to work in the linux box where
* this app is deployed.
* So I'm artificially forcing it here, as if it were a command line argument.
*
* See: https://docs.spring.io/spring-boot/docs/1.5.10.RELEASE/reference/htmlsingle/#boot-features-external-config-application-property-files
*/
args = includeConfigName(args, CONFIG_NAME);
SpringApplication.run(mainClass, args);
}
private static String[] includeConfigName(String[] args, String configName) {
String arg = "--spring.config.name";
for (String a: args) {
if (a.startsWith(arg)) {
/*
* Argument was supplied, use it as supplied.
*/
System.out.println("Using config from command line argument: " + a);
return args;
}
}
/*
* Forcefully include an arg into the command line.
*/
String args2[] = new String[args.length + 1];
System.arraycopy(args, 0, args2, 0, args.length);
String newArg = arg + "=" + configName;
args2[args2.length - 1] = newArg;
System.out.println("Force config: " + newArg);
return args2;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment