最近最项目:由于用到了太多的路径,动态写也不大方便(由于后期肯定要改)
所以刚开始为了测试直接写死了:由于越来越多,将来修改写来也不太好找,就专门做了一个.properties文件如下图:
一:新建一个.properties文件
二:然后就是要在applicationContext.xml中配置.properties的扫描
三:封装javaBean
四:用Junit测试:
五:测试,控制台输出如下:
说明配置文件已经正确加载,可以使用了…….
在网上看到的其他的一些方式:
方法一:
- public static String getValue(String fileNamePath, String key)throws IOException {
- Properties props = new Properties();
- InputStream in = null;
- try {
- in = new FileInputStream(fileNamePath);
- // 如果将in改为下面的方法,必须要将.Properties文件和此class类文件放在同一个包中
- //in = propertiesTools.class.getResourceAsStream(fileNamePath);
- props.load(in);
- String value = props.getProperty(key);
- // 有乱码时要进行重新编码
- // new String(props.getProperty("name").getBytes("ISO-8859-1"), "GBK");
- return value;
- } catch (IOException e) {
- e.printStackTrace();
- return null;
- } finally {
- if (null != in)
- in.close();
- }
- }
方法二:
通过spring配置properties文件
- <bean id="propertyConfigurer"
- class="com.hapishop.util.ProjectDBinfoConfigurer">
- <property name="ignoreResourceNotFound" value="true" />
- <property name="locations">
- <list>
- <value>app.properties</value>
- </list>
- </property>
- </bean>
自定义PropertiesConfigurer
- 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 PorpertiesConfigurer extends PropertyPlaceholderConfigurer {
- private static Map ctxPropertiesMap;
- @Override
- protected void processProperties(
- ConfigurableListableBeanFactory beanFactoryToProcess,
- Properties props) throws BeansException {
- super.processProperties(beanFactoryToProcess, props);
- ctxPropertiesMap = new HashMap();
- 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);
- }
- }
通过.properties集中管理spring框架中的路径
最新推荐文章于 2022-10-20 20:43:28 发布