【发布时间】:2011-10-19 14:42:49
【问题描述】:
在 Spring ApplicationContext 中使用属性文件时,可以通过以下方式访问其属性:在您的 xml 配置文件中使用 ${someproperty}。但是如何在不通过 xml 注入的情况下访问 java 代码中的相同属性?
ApplicationContext 配置
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="myapp.properties" />
</bean>
<bean class="my.app.MyClass">
<property name="foo" value="${someproperty}" />
</bean>
</beans>
属性
someproperty=somevalue
更新 1
实际的一点是,在属性文件中设置了应用程序的唯一 ID(例如由系统管理员编辑)的特殊情况。一些应用程序类实现了 ApplicationContextAware,因此它们可以访问上下文并防止在每个类中注入或为我们想要一个 ez 属性访问方法的每个类定义一个 bean。在这种情况下,我们的应用程序“了解”Spring 不是问题。
【问题讨论】:
-
你能解释一下“防止在每个类中注入或为每个类定义一个bean”吗?
-
如果我们不使用注释,每个需要访问属性本身的 bean 都需要一个“属性”标签。它只是将工作从类移动到 xml。
-
我实际上倾向于使用类似这篇博文中的配置类:chrislovecnm.com/2010/03/08/…