您的位置:首页 > 编程语言 > Java开发

如何在java对象里访问Spring中已加载的property内容

2011-06-30 18:27 429 查看

Exposing the spring properties bean in java

To allow our Java classes to access the properties from the same
object as spring, we’ll need to extend the PropertyPlaceholderConfigurer
so that we can provide a more convenient method for retrieving the
properties (there is no direct method of retrieving properties!).

We can extend the spring provided class to allow us to reuse spring’s property resolver in our Java classes:

01

public

class

PropertiesUtil

extends

PropertyPlaceholderConfigurer {

02


private

static

Map propertiesMap;

03

04


@Override

05


protected

void

processProperties(ConfigurableListableBeanFactory beanFactory,

06

 

Properties props)

throws

BeansException {

07

  

super

.processProperties(beanFactory, props);

08

09

  

propertiesMap =

new

HashMap<String, String>();

10

  

for

(Object key : props.keySet()) {

11


String keyStr = key.toString();

12


propertiesMap.put(keyStr, parseStringValue(props.getProperty(keyStr),

13

 

props,

new

HashSet()));

14

  

}

15

 

}

16

17

 

public

static

String getProperty(String name) {

18

  

return

propertiesMap.get(name);

19

 

}

20

}

If we now update the applicationProperties bean to use the
PropertiesUtilclass, we can use the static getProperty method to access
the resolved properties via the same object as the spring configuration
bean.

Of course, we could run into problems if a class tries to use
PropertiesUtilbefore the spring context has been initialised. For
example if you’re registering ServletContextListeners in your web.xml
before configuring spring, you’ll get a NullPointerException if one of
those classes tries to use PropertiesUtil. For that reason I’ve had to
declare the spring context before any context listeners.

view source
print
?

01

<

context-param

>

02

 

<

param-name

>contextConfigLocation</

param-name

>

03

 

<

param-value

>

04

  

/WEB-INF/applicationContext.xml

05

 

</

param-value

>

06

</

context-param

>

07

08

<

listener

>

09

 

<

listener-class

>org.springframework.web.context.ContextLoaderListener</

listener-class

>

10

</

listener

>

11

12

<!-- Other listeners -->

References

http://www.jdocs.com/spring/1.2.8/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.html

http://j2eecookbook.blogspot.com/2007/07/accessing-properties-loaded-via-spring.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐