如何在我的类中的spring bean类中获取属性值?

ant*_*h.k 5 java spring properties

我做的事情是:

  • 创建了一个属性文件(data.properties).
  • 创建了一个Spring.xml(我使用了属性占位符)
  • 创建了一个bean类.
  • 我有一个类,我必须使用url值.
  • 我有一个web.xml,它有context-param,我将param值设置为Spring.xml文件的路径.
  • 我的代码如下:

Propertyfile:URL = SAMPLEURL

Spring.xml:

<bean
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations" value="classpath*:data.properties*"/>

</bean>

<bean id="dataSource" class="org.tempuri.DataBeanClass">
    <property name="url" value="${url}"></property>
</bean>
Run Code Online (Sandbox Code Playgroud)

beanclass

public class DataBeanClass extends PropertyPlaceholderConfigurer{
private String url;

public String getUrl() {
    return url;
}

public void setUrl(String url) {
    this.url = url;
}
}
Run Code Online (Sandbox Code Playgroud)

web.xml中的条目

 <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:Spring*.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Run Code Online (Sandbox Code Playgroud)

现在我的问题是我不知道我应该覆盖什么方法的PropertyPlaceholderConfigurer,我该怎么做才能设置变量url的值,以便我可以使用getproperty()方法从其他类中调用它.

ssk*_*ssk 12

你可以像这样注释你的bean属性,然后spring会自动从你的属性文件中注入属性.

@Value("${url}")
private String url;
Run Code Online (Sandbox Code Playgroud)

您不必扩展PropertyPlaceholderConfigurer

像这样定义你的bean也会自动填充url,但是注释似乎是最简单的方法

<bean id="dataSource" class="org.tempuri.DataBeanClass">
   <property name="url" value="${url}"></property>
</bean>
Run Code Online (Sandbox Code Playgroud)