2017-10-17 7 views
3

스프링 프레임 워크에만 포트 번호, 컨텍스트 루트 경로, 애플리케이션 이름과 같은 속성이server.yml 파일이 있습니다.스프링 부트의 클래스 패스에 파일 추가하기

는, 나는 다음과 같은이있는 applicationContext.xml 있습니다

<util:properties id="springProperties" location="classpath*:my.properties"> 
<context:property-placeholder location="classpath*:my.properties" 
     local-override="true" properties-ref="springProperties" /> 

my.properties 파일은 프로젝트의 src/main/resources 디렉토리에 있습니다. 나는 전쟁을 빌드 할 때

@Autowired 
@Qualifier("springProperties") 
private Properties props; 

public String getProperty(String key){ 
    return props.getProperty(key); 
} 

or like `${my.prop}` 

그리고 봄 부팅 (java -jar server.war), 내부 my.properties 결의를 실행하고 모든 것이 예상대로 작동합니다 :

는 그럼, 내가 좋아하는 내 자바 클래스에서 속성에 액세스 할 수 있습니다.

그러나이 파일을 외부 my.properties으로 덮어 쓰고 싶었습니다.

java -jar server.jar --spring.config.location=classpath:/my.properties 또는

java -jar server.jar --spring.config.location=my.properties

하지만 이것에 의해 오버라이드 (override) 할 수있는 유일한 속성 내 server.yml에서있다 : 나는 내가 좋아하는 뭔가를 실행하려고

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html를 참조하십시오. 의미, 포트 번호 또는 응용 프로그램 이름을 무시할 수 있습니다. 그러나 내부 my.properties은 영향을받지 않습니다.

내가 잘못 했나요? 외부 my.property이 클래스 패스에 있어야한다는 것을 이해하고 내부 my.property을 무시합니다. 그러나 결코 일어나지 않습니다.

+0

이 구성에서는 'springProperties'의 한정자없이이 작업을 시도 했습니까? 외부 적으로로드하고있는 my.properties의 복사본은 해당 컨텍스트에 영향을 미치지 않습니다. – dillius

답변

1

당신은 @PropertySource 사용할 수 있습니다 클래스 경로에서 파일을 추가 할 ({ "클래스 경로 override.properties을"}) 다음 값

@PropertySource({ "classpath:other.properties" }) 
@Configuration 
public class Config{ 
    @Autowired 
    private Environment env; //use env.getProperty("my.prop") 

    @Value("${my.prop}") 
    private String allowedpatterns; 
} 

@Component 
public OthenClass{ 

    @Autowired 
    //If this class is not component or Spring annotated class then get it from ApplicationContext 
    private Environment env; //use env.getProperty("my.prop") 

    @Value("${my.prop}") 
    private String allowedpatterns; 
} 

만약의 값 또는 @Value 주석을 얻기 위해 환경 객체를 사용하여 당신은 Spring 부트를 사용하고 있습니다. 아래 코드를 사용하면 ApplicationContext를 얻을 수 있습니다.

ConfigurableApplicationContext ctx = app.run(args); 

Environment env = ctx.getBean(Environment.class); 
+0

위와 같이 실행 한 후에는 다음을 실행해야합니다. 'java -jar server.jar --spring.config.location = my.properties' – yeralin

+0

resources 디렉토리에도 특성 파일을 넣을 수 있습니다. 스프링 부트는 클래스 경로에서 파일을 가져옵니다. – Debopam

관련 문제