내용으로 건너뛰기
권남
사용자 도구
로그인
사이트 도구
검색
도구
문서 보기
이전 판
역링크
최근 바뀜
미디어 관리자
사이트맵
로그인
>
최근 바뀜
미디어 관리자
사이트맵
추적:
springframework:propertysource
이 문서는 읽기 전용입니다. 원본을 볼 수는 있지만 바꿀 수는 없습니다. 문제가 있다고 생각하면 관리자에게 문의하세요.
====== PropertySource ====== * [[http://blog.springsource.org/2011/02/15/spring-3-1-m1-unified-property-management/|Spring 3.1 M1: Unified Property Management]] * Spring 3.1 부터 생기기 시작한 통합 프라퍼티 관리 시스템 * 시스템 프라퍼티, 환경변수, JNDI 등을 모두 하나의 공간에 넣고 그 값을 읽고 설정할 수 있게 해준다. * [[http://scottfrederick.blogspot.kr/2012/03/custom-propertysource-in-spring-31.html|Custom PropertySource in Spring 3.1]] : 프라퍼티 소스에 Redis의 데이터를 추가하는 예제 * [[http://blog.codeleak.pl/2015/09/placeholders-support-in-value.html|${... } placeholders support in @Value annotations in Spring]] ===== 프라퍼티 추가 ===== * 일반 프라퍼티 파일의 경우 * Java 클래스 설정에서는 [[http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/context/annotation/PropertySource.html|@PropertySource]]로 프라퍼티 파일을 지정하거나, * <del>[[http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/xsd-config.html#xsd-config-body-schemas-context-pphc|<context:property-placeholder> tag]]를 사용해 넣을 수 있다.</del> - 이거 안 된다. 하단 참조. ===== 코딩을 통한 임의의 프라퍼티 소스 추가 ===== * ''MyPropertySource''가 [[http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/core/env/PropertySource.html|PropertySource]] 구현체 일 때 ==== 일반 Java 애플리케이션 ==== <code java> ConfigurableApplicationContext ctx = new GenericApplicationContext(); MutablePropertySources sources = ctx.getEnvironment().getPropertySources(); sources.addFirst(new MyPropertySource()); </code> ==== 웹 애플리케이션 ==== * ''web.xml''<code xml> <context-param> <param-name>contextInitializerClasses</param-name> <param-value>com.bank.MyInitializer</param-value> </context-param> </code> * TestContext에서 ''web.xml''없이 Java Code로 등록하기<code java> @ContextConfiguration(initializers = MyInitializer.class) </code> * ''MyInitializer.java''<code java> public class MyInitializer implements ApplicationContextInitializer<ConfigurableWebApplicationContext> { public void initialize(ConfigurableWebApplicationContext ctx) { PropertySource ps = new MyPropertySource(); ctx.getEnvironment().getPropertySources().addFirst(ps); // perform any other initialization of the context ... } } </code> ==== ApplicationContextInitializer를 Java 코드 기반 ApplicationContext에서 사용하기 ==== * [[http://stackoverflow.com/questions/13288841/applicationcontextinitializer-in-a-non-web-spring-context|java - ApplicationContextInitializer in a non-web Spring Context?]]<code java> // Create context, but dont initialize with configuration by calling // the empty constructor. Instead, initialize it with the Context Initializer. AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); MyAppContextInitializer initializer = new MyAppContextInitializer(); // ApplicationContextInitializer가 ApplicationContext를 초기화해주는 형태 initializer.initialize( ctx ); // @Configuration 클래스를 등록하고 초기화 ctx.register( com.my.classpath.StackOverflowConfiguration.class ); ctx.refresh() </code> ==== @Configuration 클래스에서 XML 프라퍼티를 프라퍼티 소스로 등록하기 예제 ==== **3.2 최신 버전에서는 이 기법을 사용할 필요가 없다. ApplicationContextInitializer를 사용하자.** 현재(3.1.2) ''@PropertySource''를 통해서는 XML 프라퍼티를 등록할 수 없는 상태인데, ''@Configuration'' Java 클래스에서 직접 등록할 수 있다. [[http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/context/ConfigurableApplicationContext.html|ConfigurableApplicationContext]]를 주입 받은 것에 주의하라. ApplicationContext로 주입 받으면 안 된다. 프라퍼티 소스의 이름도 겹치면 안 된다. <code java> @Configuration public class SpringConfig { @Autowired private org.springframework.context.ConfigurableApplicationContext applicationContext; @Autowired private org.springframework.core.io.ResourceLoader resourceLoader; @PostConstruct public void addXmlProperties() throws Exception { addXmlProperties("classpath:my-properties.xml"); addXmlProperties("classpath:my-properties2.xml"); } private void addXmlProperties(String location) throws IOException, InvalidPropertiesFormatException { Resource resource = resourceLoader.getResource(location); Properties properties = new Properties(); properties.loadFromXML(resource.getInputStream()); applicationContext .getEnvironment() .getPropertySources() .addLast( new PropertiesPropertySource( getNameForResource(resource), properties)); } // from ResourcePropertySource private static String getNameForResource(Resource resource) { String name = resource.getDescription(); if (!StringUtils.hasText(name)) { name = resource.getClass().getSimpleName() + "@" + System.identityHashCode(resource); } return name; } @Bean public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } } </code> ===== PlaceHolder로 사용하기 ===== PropertySource에 등록된 프라퍼티들을 ''@Value("${property.name}")'' 형태로 사용하려면 [[http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/context/support/PropertySourcesPlaceholderConfigurer.html|PropertySourcesPlaceholderConfigurer]] 등록이 필요하다. * Java 코드 설정시<code java> @Configuration @PropertySource("my.properties") public class SpringConfig { @Bean public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } } </code> * XML로 설정시<code xml> <context:property-placeholder location="classpath:my-properties.xml"/> <!-- <context:property-placeholder/>는 Spring 3.1에서는 PropertySourcePlaceholderConfigurer 로 초기화된다. 이 때 location에 지정된 프라퍼티도 place-holder로 적용하게 된다. 현재(Spring 3.1.2)에는 XML Property를 못 추가하는 버그가 있는데 이를 통해 우회 가능하다. 단, 이렇게 location에 들어간 프라퍼티는 공식 Environment의 PropertySource로 추가되지는 않는다. 따라서 org.springframework.core.env.Environment.getProperty()로는 읽을 수 없다. 가능하면 위에 설명한 @Configuration Java 클래스에서 프라퍼티 소스 등록하기 예제를 사용하는게 낫다. @ 확인 필요 : 이 경우 자식 ApplicationContext에서도 location에 지정된 프라퍼티는 place-holder로 사용할 수 없을 것이다. @ --> </code> ===== ResourceLoader ===== * ''@Autowired ResourceLoader resourceLoader'' 로 현재 애플리케이션 컨텍스트의 [[http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/io/ResourceLoader.html|ResourceLoader]]를 획득하여 사용할 수 있다. * 단, ''classpath:/package/to/**/*.xml'' 처럼 Pattern화된 Resource를 로딩할 때는 [[http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/io/support/ResourcePatternResolver.html|ResourcePatternResolver]]를 주입받아서 [[http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/io/support/ResourcePatternResolver.html#getResources-java.lang.String-|ResourcePatternResolver#getResources()]] 메소드로 패턴을 해석한 결과를 획득해야 한다. * 그냥 속 편하게 [[http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/ApplicationContext.html|ApplicationContext]]를 주입 받으면 이것 자체가 ''ResourcePatternResolver''를 구현하므로 이를 사용하도 된다. ===== @Value ===== ==== @Value로 Date 객체 주입하기 ==== * [[http://stackoverflow.com/questions/18066482/inject-date-using-value-annotation|spring - Inject date using @Value annotation - Stack Overflow]]<code java> @Value("#{new java.text.SimpleDateFormat(\"yyyyMMdd\").parse(\"${PROP_DATE}\")}") private Date date; </code> * [[http://www.baeldung.com/spring-value-defaults|Using Spring @Value with Defaults]]
springframework/propertysource.txt
· 마지막으로 수정됨: 2017/08/11 09:04 저자
kwon37xi
문서 도구
문서 보기
이전 판
역링크
맨 위로