【问题标题】:How to get the property value inside a spring bean class in my class ?如何在我的类中获取 spring bean 类中的属性值?
【发布时间】:2013-11-27 01:08:13
【问题描述】:

我做的事情是:

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

属性文件: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>

豆类

public class DataBeanClass extends PropertyPlaceholderConfigurer{
private String url;

public String getUrl() {
    return url;
}

public void setUrl(String url) {
    this.url = url;
}
}

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>

现在我的问题是我不知道我应该重写 PropertyPlaceholderConfigurer 的哪个方法以及我应该如何设置变量 url 的值以便我可以使用 getproperty() 方法从其他类调用它。

【问题讨论】:

  • 我不明白你的问题。
  • 问题是我被告知我的 bean 类应该扩展某个类,并且我应该重写它的一个方法,以便我可以在其他一些类中使用属​​性值。我假设要扩展的类是 PropertyPlaceholderConfigurer。不过,我不是 100% 确定。
  • 由于您的“url”值已经存在于属性文件中,我认为您想在多个 bean 类中使用该属性。
  • 你是如何创建 bean 对象的?它是从 Spring ApplicationContext 创建的还是使用“new”创建的
  • 您也可以随时使用context = ContextLoader.getCurrentWebApplicationContext(); 来加载容器初始化期间创建的相同上下文。

标签: java spring properties


【解决方案1】:

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

@Value("${url}")
private String url;

您不必扩展 PropertyPlaceholderConfigurer

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

<bean id="dataSource" class="org.tempuri.DataBeanClass">
   <property name="url" value="${url}"></property>
</bean>

【讨论】:

  • 如果我要扩展 PropertyPlaceHolderConfigurer 我应该怎么做?
【解决方案2】:

可以通过 Spring.xml 中的以下命名空间元素使 Spring 可以访问属性文件

<context:property-placeholder location="classpath:data.properties" />

然后你可以使用like

@Autowired
private Environment env;
...
String url=env.getProperty("url"));

注意:

使用 &lt;property-placeholder&gt; 不会将属性暴露给 Spring 环境——这意味着像这样检索值将不起作用——它将返回 null

【讨论】:

  • 但是如果 env.getProperty("url")) 不起作用,那有什么意义呢?
【解决方案3】:

请执行以下过程以获取类中的属性文件值。

  1. 在 spring.xml 中为属性文件定义 bean
    &lt;util:properties id="dataProperties" location="classpath:/data.properties"/&gt;

  2. 将 data.properties 保存在 src/main/resources 下。

  3. 使用以下代码从属性文件中获取值,例如获取 data.properties 中 url 键的值

private @Value("#{dataProperties['url']})
String url;

【讨论】:

    猜你喜欢
    • 2018-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-03
    • 1970-01-01
    • 1970-01-01
    • 2010-10-08
    • 2022-11-10
    相关资源
    最近更新 更多