package com.test.utils;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
public class CustomPropertyConfig extends PropertyPlaceholderConfigurer{
private static Map<String, Object> ctxPropertiesMap;
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess,Properties props) throws BeansException {
super.processProperties(beanFactoryToProcess, props);
ctxPropertiesMap = new HashMap<String, Object>();
for (Object key : props.keySet()) {
String keyStr = key.toString();
String value = props.getProperty(keyStr);
ctxPropertiesMap.put(keyStr, value);
}
}
public static Object getContextProperty(String name) {
return ctxPropertiesMap.get(name);
}
}
<bean id="propertyConfigurer"
class="com.test.utils.CustomPropertyConfig">
<property name="locations">
<list>
<!-- org.springframework.beans.factory.config.PropertyPlaceholderConfigurer这里支持多种寻址方式:classpath和file -->
<!-- 推荐使用file的方式引入,这样可以将配置和代码分离 -->
<!-- <value>classpath:jdbc.properties</value> -->
<value>classpath:dbconfig.properties</value>
</list>
</property>
</bean>
加载配置文件String secretKey = (String) CustomPropertyConfig.getContextProperty("secretKey");
有时候用多线程的时候对象无法注入需要从spring容器中获取对象
配置文件:
<bean id="student" class="com.test.controller.Student"> </bean>
<bean id="SpringConfigTool" class="com.test.utils.SpringConfigTool"/>
package com.test.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class SpringConfigTool implements ApplicationContextAware{
private static ApplicationContext context = null;
private static SpringConfigTool stools = null;
public synchronized static SpringConfigTool init() {
if (stools == null) {
stools = new SpringConfigTool();
}
return stools;
}
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
context = applicationContext;
}
public synchronized static Object getBean(String beanName) {
return context.getBean(beanName);
}
}
Student s = (Student)SpringConfigTool.getBean("student");
s.show1("111");
or
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"classpath:application.xml"});
ctx.start();
HelloService helloservice = (HelloService)ctx.getBean("helloService");
System.out.println(helloservice.getName());
}