如何使用spring 2.5.x将单个属性值注入字符串?

kro*_*old 6 java spring

我真的想注释一个方法,引用属性文件中的单个属性进行注入.

@Resource("${my.service.url}")
private String myServiceUrl;
Run Code Online (Sandbox Code Playgroud)

当然,这种语法不起作用;)这就是为什么我在这里问.

我知道我可以注入完整的属性文件,但这似乎过多,我不想要属性文件 - 我想要配置的值.

编辑:我只能看到PropertyPlaceholderConfigurer示例,其中使用XML将属性连接到给定字段.我仍然无法弄清楚如何通过注释实现这一目标?

小智 7

我知道自从原始帖子以来已经有一段时间了,但是我已经设法在Spring 2.5.x中遇到了这个问题的解决方案

您可以在spring xml配置中创建"String"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>
Run Code Online (Sandbox Code Playgroud)


Ric*_*ell 5

我已经创建了一个解决Spring 2.5的这个问题的项目.*:

http://code.google.com/p/spring-property-annotations/

对于Spring 3,您可以使用@Value("$ {propery.key}")注释.


Dón*_*nal 4

Spring 论坛上有一个关于此的主题。简而言之,实际上没有办法使用注释注入单个属性。

我听说 Spring 3.0 将改进对使用注释的支持,所以这个问题很可能很快就会得到解决。