我有这个,
import org.apache.log4j.Logger;
@Configuration
@PropertySource("classpath:abc.properties")
public class AbcConfig {
@Value("${test.testLogger}")
private Logger logger;
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigIn() {
return new PropertySourcesPlaceholderConfigurer();
}
然后在我的java代码中,我希望在使用Properties创建AnnotationContext时传入该类的Logger,
context = new AnnotationConfigApplicationContext();
Properties prop = new Properties();
prop.put("test.testLogger", getLogger());
context.getEnvironment().getPropertySources().addLast(new PropertiesPropertySource("test", prop));
context.register(AbcConfig.class);
context.refresh();
不幸的是,当我运行这个时,我得到以下异常,
Caused by: java.lang.IllegalArgumentException: Cannot convert value [org.apache.log4j.Logger@5f015823] from source type [Logger] to target type [String]
at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:84)
at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:59)
at org.springframework.core.env.AbstractEnvironment.getProperty(AbstractEnvironment.java:427)
at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$1.getProperty(PropertySourcesPlaceholderConfigurer.java:131)
at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$1.getProperty(PropertySourcesPlaceholderConfigurer.java:128)
at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:73)
at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:59)
at org.springframework.core.env.AbstractPropertyResolver$1.resolvePlaceholder(AbstractPropertyResolver.java:176)
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:146)
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:125)
at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:174)
at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:143)
at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$2.resolveStringValue(PropertySourcesPlaceholderConfigurer.java:167)
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:755)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:778)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
... 32 more
所以在我看来,使用@Value只适用于String(也许是整数)。 这是使用Spring 3.2.2。 是否有解决方法(使用Logger或任何其他非字符串对象)?