簡體   English   中英

如何使用spring 2.5.x將單個屬性值注入字符串?

[英]How do I inject a single property value into a string using spring 2.5.x?

我真的想注釋一個方法,引用屬性文件中的單個屬性進行注入。

@Resource("${my.service.url}")
private String myServiceUrl;

當然,這種語法不起作用;)這就是為什么我在這里問。

我知道我可以注入完整的屬性文件,但這似乎過多,我不想要屬性文件 - 我想要配置的值。

編輯:我只能看到PropertyPlaceholderConfigurer示例,其中使用XML將屬性連接到給定字段。 我仍然無法弄清楚如何通過注釋實現這一目標?

我知道自從原始帖子以來已經有一段時間了,但是我已經設法在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>

我已經創建了一個解決Spring 2.5的這個問題的項目。*:

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

對於Spring 3,您可以使用@Value(“$ {propery.key}”)注釋。

Spring論壇上有一個關於這個的帖子 簡短的回答是,沒有辦法使用注釋注入單個屬性。

我聽說在Spring 3.0中對使用注釋的支持將得到改進,所以很可能很快就會解決這個問題。

如果使用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中的字段。

請查看: http//static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-factory-placeholderconfigurer

HTH。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM