2014-09-26 3 views
4

Spring의 @Value 주석을 사용하여 맞춤 클래스 유형의 속성 값을 읽고 쓸 수 있습니까? 예를 들어맞춤 클래스의 Spring @Value 속성

: 나는 봄 4.x의 API를 사용하여 그것을 어떻게

@Component 
@PropertySource("classpath:/data.properties") 
public class CustomerService { 

    @Value("${data.isWaiting:#{false}}") 
    private Boolean isWaiting; 

    // is this possible for a custom class like Customer??? 
    // Something behind the scenes that converts Custom object to/from property file's string value via an ObjectFactory or something like that? 
    @Value("${data.customer:#{null}}") 
    private Customer customer; 

    ... 
} 

EDITED 솔루션 여기

은 ...입니다

고객 클래스 만든 새로운 PropertyEditorSupport 클래스 :

public class CustomerPropertiesEditor extends PropertyEditorSupport { 

    // simple mapping class to convert Customer to String and vice-versa. 
    private CustomerMap map; 

    @Override 
    public String getAsText() 
    { 
     Customer customer = (Customer) this.getValue(); 
     return map.transform(customer); 
    } 

    @Override 
    public void setAsText(String text) throws IllegalArgumentException 
    { 
     Customer customer = map.transform(text); 
     super.setValue(customer); 
    } 
} 

그런 다음 응용 프로그램 ATION의 ApplicationConfig 클래스 :

@Bean 
public CustomEditorConfigurer customEditorConfigurer() { 

    Map<Class<?>, Class<? extends PropertyEditor>> customEditors = 
      new HashMap<Class<?>, Class<? extends PropertyEditor>>(1); 
    customEditors.put(Customer.class, CustomerPropertiesEditor.class); 

    CustomEditorConfigurer configurer = new CustomEditorConfigurer(); 
    configurer.setCustomEditors(customEditors); 

    return configurer; 
} 

건배, 오후

답변

5

자세한 사항 당신은 PropertyEditorSupport를 확장하는 클래스를 만들어야합니다.

public class CustomerEditor extends PropertyEditorSupport { 
    @Override 
    public void setAsText(String text) { 
    Customer c = new Customer(); 
    // Parse text and set customer fields... 
    setValue(c); 
    } 
} 
+0

감사합니다. 그게 내가 찾고 있던거야. 완전한 솔루션을 보여주기 위해 초기 게시물을 수정하고 있습니다. –

1

그것은 가능하지만 봄 문서를 읽고 있습니다. 이 예제를 볼 수 있습니다 : 사용 예제

@Configuration 
@PropertySource("classpath:/com/myco/app.properties") 
public class AppConfig { 
    @Autowired 
    Environment env; 

    @Bean 
    public TestBean testBean() { 
     TestBean testBean = new TestBean(); 
     testBean.setName(env.getProperty("testbean.name")); 
     return testBean; 
    } 
} 

참조가 here

관련 문제