题
我真的想注释一个方法,引用属性文件中的单个属性进行注入。
@Resource("${my.service.url}")
private String myServiceUrl;
当然,这种语法不起作用;)这就是为什么我在这里问。
我知道我可以注入完整的属性文件,但这似乎太过分了,我不想要属性文件 - 我想要配置的值。
编辑:我只能看到PropertyPlaceholderConfigurer示例,其中使用XML将属性连接到给定字段。我仍然无法弄清楚如何通过注释实现这一目标?
解决方案
在 Spring论坛上有一个关于此问题的主题。简短的回答是,没有办法使用注释注入单个属性。
我听说在Spring 3.0中对使用注释的支持会有所改进,所以很可能会很快解决这个问题。
其他提示
我知道自原始帖子以来已经有一段时间了,但我已经设法在Spring 2.5.x中遇到了解决这个问题的解决方案
您可以创建“String”的实例spring xml配置中的bean,然后可以注入Annotated组件
@Component
public class SomeCompent{
@Autowired(required=true
@Resource("someStringBeanId")
private String aProperty;
...
}
<beans ....>
<context:component-scan base-package="..."/>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
...
</bean>
<bean id="someStringId" class="java.lang.String" factory-method="valueOf">
<constructor-arg value="${place-holder}"/>
</bean>
</beans>
我创建了一个针对Spring 2.5解决此问题的项目。*:
http://code.google.com/p/spring-property-annotations /
对于Spring 3,您可以使用@Value(&quot; $ {propery.key}&quot;)注释。
如果使用XML配置,则可以执行此操作。只需配置PropertyPlaceholderConfigurer并在配置
中指定属性值<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:com/foo/jdbc.properties</value>
</property>
</bean>
<bean ...>
<property name="myServiceUrl" value="${my.service.url}"/>
</bean>
您可以尝试注入属性值“my.service.url”在你的bean中提交。
HTH。
不隶属于 StackOverflow