Spring boot/Spring
08. spring - properties 관리
akatjd
2022. 7. 12. 17:51
맨날 까먹어서 구글링하기 귀찮아서 정리
*.properties 안에 value 값들을 지정해서 관리할때 property config 구성 후 bean 등록을 통해 value 값을 접근할 수 있다.
example config
@Configuration
public class PropertyConfig {
@Bean(name = "key")
public PropertiesFactoryBean propertiesFactoryBean() throws Exception{
PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
ClassPathResource classPathResource = new ClassPathResource("key.properties");
propertiesFactoryBean.setLocation(classPathResource);
return propertiesFactoryBean;
}
}
ClassPathResource에 properties 접근 경로를 적어준다. (resource 바로 밑에 뒀으므로 바로 파일명을 적은거고 하위 폴더를 더 만들었다면 /properties/key.properties 이런식을로 작성하면 된다.)
import org.springframework.beans.factory.annotation.Value;
@Value("#{key['user.api_key']}")
private String accessKey;
value 어노테이션을 통해 properties 값을 불러올 수 있다.
properties value는 단일 값이 아닌 다중 값도 배열 형식으로 불러 올 수 있는 점 참고.