框架Spring + SpringMVC
1、@Value()在对象上获取properties的值
@Value("${micro.regist.host}")
private String testParam;
配置文件server.properties配置一条
micro.regist.host=http://172.16.1.42:8081/smsp/
applicationContext.xml配置
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:server.properties" />
</bean>
在这里配置完毕。@Controller获取不到 @Service可以获取
因为@Controller是springMVC容器管理
@Service@Dao由spring容器管理
applicationContext.xml配置在spring上,所以要在springMVC配置文件也加上配置。
配置如下:
<context:property-placeholder location="classpath:server.properties" ignore-unresolvable="true"/>
<!-- 默认的注解映射的支持 -->
<mvc:annotation-driven />
<context:component-scan base-package="com.jiuyv" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
这样@Controller和@Service都可以访问properties配置了
方法2、使用加载方式获取properties配置
直接上代码:
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import org.apache.log4j.Logger;
/**
*
*
* @author xiaoxiang
* @version $Id: ConfigurableContants.java, v 0.1 2016年11月22日 下午4:06:31 Administrator Exp $
*/
public class ConfigurableContants {
private static final Logger logger = Logger.getLogger(ConfigurableContants.class);
protected static Properties p = new Properties();
protected static String propertyFilePath = null;
protected static void init(String propertyFileName) {
InputStream in = null;
try {
in = ConfigurableContants.class.getResourceAsStream(propertyFileName);
if (in != null)
p.load(in);
} catch (IOException e) {
logger.error("load " + propertyFileName + " into Contants error");
} finally {
if (in != null) {
try {
propertyFilePath = propertyFileName;
in.close();
} catch (IOException e) {
}
}
}
}
protected static String getProperty(String key, String defaultValue) {
return p.getProperty(key, defaultValue);
}
protected static String getProperty(String key) {
return getProperty(key, "");
}
/**
* 取以","分割的集合属性
*
* @param key
* @param defaultValue
* @return
*/
protected static Set<String> getSetProperty(String key, String defaultValue) {
String[] strings = p.getProperty(key, defaultValue).split(",");
HashSet<String> hashSet = new HashSet<String>(strings.length);
for (String string : strings) {
hashSet.add(string.trim());
}
return hashSet;
}
protected static Set<String> getSetProperty(String key) {
return getSetProperty(key, "");
}
protected static void refreshInit() {
init(propertyFilePath);
}
}