Spring Boot でプロパティファイルを外部ファイル化する

プロパティファイルを外部ファイル化したい。
さらにファイル名に application.properties は使えないという条件。


Application.java

package hello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.MessageSource;

@SpringBootApplication
public class Application implements CommandLineRunner {
    
	@Autowired
	GreedInterface greedInterface;
	
	@Autowired
	MessageSource messageSource;
	
	public static void main(String[] args) throws Exception {
		SpringApplication application = new SpringApplication(Application.class);
		application.setShowBanner(false);
		application.run(args);
    }

	@Override
	public void run(String... args) throws Exception {
		System.out.println(greedInterface.greed());
	}
}

GreedInterface.java

package hello;

public interface GreedInterface {
    
    public String greed();
}

HelloService.java

package hello.impl;

import hello.GreedInterface;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

@PropertySource("${spring.config.basepath}")
@Service
public class HelloService implements GreedInterface {

	@Value("${message}")
	private String message;
	
	@Override
	public String greed() {
		return message;
	}

}

src/main/resources/default.properties

message=default

../../override/override.properties

message=override

jar実行

$ java -jar spring-boot-value-0.1.0.jar --spring.config.basepath=classpath:default.properties
default

jar実行

$ java -jar spring-boot-value-0.1.0.jar --spring.config.basepath=file:../override/override.properties
override