spring配置文件

1.spring读取配置文件的地址,如果没有特定的声明那么一般都是从classpath:(对应项目中的资源根目录)下面进行读取,读取的方式有两种

1)在需要的部分的类上直接采用加载,这样这一个文件只能够在这一个类下面才可以读取到内容

     读取方式:@PropertySource("classpath:public.properties")

2)在配置文件中直接将需要的配置文件进行加载

    加载方式: 

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<!--加载配置文件,这里可以加载多个配置文件-->
<value>classpath:public.properties</value>
</list>
</property>
</bean>

2.读取的配置文件在项目外面,项目的配置文件如果没有放到资源的根路径下,那么就需要进行自行设定需要读取的位置。设置的方式有两种,一种是在配置文件中进行设置加载,一种是通过代码来进行加载。

其实所谓的分为在项目内部和外面读取配置文件的方式,只是说spring为我们读取资源根路径的时候做了一个简易的处理,可以直接读取classpath下面的文件,当然我们也可以不是用这种简化的方式,让配置文件每一次

都是进入我们需要的目录下面进行读取。

1)通过配置文件来读取

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>file:${user.dir}/public.properties</value>
</list>
</property>
</bean>

2)通过代码来进行读取

private static final Properties sysConfig = new Properties();

static {
try {
InputStream iStream = new FileInputStream(new File("/", "public.properties"));
sysConfig.load(iStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public static String getPropertyValue(String key) {
return sysConfig.getProperty(key);

}
${user.dir} 是属于系统的一个变量,在系统中还有多个变量,可以将变量输出来进行查看

 






posted @ 2019-08-21 09:48  virtual_c  阅读(213)  评论(0编辑  收藏  举报