01 属性文件|env.properties
02 spring-base.xml 摘要
03 SpringUtil.java
04 属性读取类|Env.java
05 使用|MemcacheManager.java
#Memcached 服务器地址
memcached.address=127.0.0.1:11211
02 spring-base.xml 摘要
<context:property-placeholder location="classpath:env.properties" />
03 SpringUtil.java
package com.xxx.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;
@Override
public void setApplicationContext(ApplicationContext appContext) throws BeansException {
if (SpringUtil.applicationContext == null) {
SpringUtil.applicationContext = appContext;
}
System.out.println("======ApplictionContext配置成功,在普通类可以用SpringUtils.getApplicationContext()获取上下文对象=====");
}
//获取applicationContext
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
//通过name获取 Bean.
public static Object getBean(String name){
return getApplicationContext().getBean(name);
}
//通过class获取Bean.
public static <T> T getBean(Class<T> clazz){
return getApplicationContext().getBean(clazz);
}
//通过name,以及Clazz返回指定的Bean
public static <T> T getBean(String name,Class<T> clazz){
return getApplicationContext().getBean(name, clazz);
}
}
04 属性读取类|Env.java
package com.xxx.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Env {
private static final Logger log = LoggerFactory.getLogger(Env.class);
private static Properties prop = getProperties();
public static String get(String key) {
return prop.getProperty(key);
}
public static Properties getProperties() {
try {
return (Properties) SpringUtil.getBean("env");
} catch (Exception e) {
Properties properties = new Properties();
try {
File file = new File(Env.class.getClassLoader().getResource("env.properties").getPath());
InputStream inputStream = new FileInputStream(file);
properties.load(inputStream);
inputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
log.info("加载配置文件:");
for (Object key : properties.keySet()) {
log.info("key:{}\tvalue:{}", key, properties.get(key));
}
log.info("加载配置文件完毕。");
return properties;
}
}
public static void reLoad() {
log.info("重新加载配置文件");
prop = getProperties();
}
}
05 使用|MemcacheManager.java
public class MemcacheManager {
private static final Logger log = LoggerFactory.getLogger(MemcacheManager.class);
static MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(Env.get("memcached.address")));
...