如何在java对象里访问Spring中已加载的property内容
2014-08-19 00:00
471 查看
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 }
Of course, we could run into problems if a class tries to use PropertiesUtil before 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 ? < context-param > < param-name >contextConfigLocation</ param-name > < param-value > /WEB-INF/applicationContext.xml </ param-value > </ context-param > < listener > < listener-class >org.springframework.web.context.ContextLoaderListener</ listener-class > </ listener > <!-- Other listeners -->
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
相关文章推荐
- 如何在java对象里访问Spring中已加载的property内容
- C#如何访问水晶报表中的对象,以及动态改变对象的内容?
- chap 17:当JNI遇到多线程--java对象如何被C++中的多个线程访问?
- Java 如何证明加载类的动作仅发生一次。证明该类的第一个实体的创建或者对static成员的访问都有可能引起加载
- controller中使用@RequestBody,Java如何传递json对象访问接口,以及对象中的时间类型
- 讲解Java中如何构造内部类对象以及访问对象
- C#如何访问水晶报表中的对象,以及动态改变对象的内容?
- java如何循环输出Object对象内容
- spring 如何动态加载properties文件的内容
- java面向对象-super、继承、覆盖、多态、类加载、访问控制
- spring 如何动态加载properties文件的内容
- Flex快速入门系列之二:FlashBuilder创建项目以及远程JAVA对象访问(包括spring)篇
- Java中如何获取spring中配置的properties属性文件内容
- 如何判断java自定义对象内容完全相同
- java 内部类如何访问外部类的对象
- 如何在JBPM的Action中访问Spring中的JavaBean
- 当JNI遇到多线程--java对象如何被C++中的多个线程访问?
- 当JNI遇到多线程--java对象如何被C++中的多个线程访问?
- 如何访问到spring代理的目标对象
- spring 的 PropertyPlaceholderConfigurer读取的属性怎么访问 (java访问方式,不是xml中的占位符哦)及此类的应用