반응형
스프링에서 @value 어노테이션에 기본값 설정
출처 : https://www.mkyong.com/spring3/spring-value-default-value/
1. @Value Examples
To set a default value in Spring expression, use Elvis operator
:
#{expression?:default value}
Few examples :
@Value("#{systemProperties['mongodb.port'] ?: 27017}")
private String mongodbPort;
@Value("#{config['mongodb.url'] ?: '127.0.0.1'}")
private String mongodbUrl;
@Value("#{aBean.age ?: 21}")
private int age;
P.S @Value
has been available since Spring 3.0
2. @Value and Property Examples
To set a default value for property placeholder :
${property:default value}
Few examples :
//@PropertySource("classpath:/config.properties}")
//@Configuration
@Value("${mongodb.url:127.0.0.1}")
private String mongodbUrl;
@Value("#{'${mongodb.url:172.0.0.1}'}")
private String mongodbUrl;
@Value("#{config['mongodb.url']?:'127.0.0.1'}")
private String mongodbUrl;
config.properties
mongodb.url=1.2.3.4
mongodb.db=hello
For “config” bean.
<util:properties id="config" location="classpath:config.properties"/>
Follow up
Must register a static PropertySourcesPlaceholderConfigurer
bean in either XML or annotation, so that Spring @Value
know how to interpret ${}
//@PropertySource("classpath:/config.properties}")
//@Configuration
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigIn() {
return new PropertySourcesPlaceholderConfigurer();
}
반응형
'개발 > Programming' 카테고리의 다른 글
Spring Security Acegi Tutorial (0) | 2017.07.20 |
---|---|
Spring에서 REST 서비스를 위한 컨트롤러에 FORM과 파일업로드(multipart/form-data)를 함께 사용하기와 컨트롤러 테스트하기 (0) | 2017.06.07 |
jstack 그리고 jconsole - JVM Stack Trace 얻기 (0) | 2017.06.07 |
Jersey File Upload Example (0) | 2017.06.02 |
Spring + java.servlet.Filter (0) | 2017.05.31 |