InputStream ips = new FileInputStream("config.properties");
//配置文件须要放在当前包目录下 InputStream ips = ReflectCollection.class .getResourceAsStream("resources/config.properties");
这种方式也能够使用绝对路径,绝对路径须要加上斜杠(/)。无论是绝对仍是相对路径,底层调用都是类加载器。java
//绝对路径的方式 InputStream ips = ReflectCollection.class .getResourceAsStream( "/cn/sunft/day01/reflect/resources/config.properties");
在classpath所在的根目录下查找文件,文件须要直接放在classpath指定的目录下,另外目录最前面不要加斜杠(/)。redis
//在classpath所在的根目录下查找文件 //注意这里的文件须要直接放在classpath指定的目录下, //另外目录最前面不要加/,经过这种方式文件一般不须要修改 InputStream ips = ReflectCollection.class .getClassLoader() .getResourceAsStream("cn/sunft/day01/reflect/config.properties")
1、经过 context:property-placeholder 标签实现配置文件加载spring
<context:property-placeholder ignore-unresolvable="true" location="classpath:redis-key.properties"/>
二、在 spring.xml 中使用配置文件属性:ide
<!-- 基本属性 url、user、password --> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" />
三、在java文件中使用: url
@Value("${jdbc_url}") private String jdbcUrl; // 注意:这里变量不能定义成static
2、经过 util:properties 标签实现配置文件加载
一、用法示例: 在spring.xml配置文件中添加标签spa
<util:properties id="util_Spring" local-override="true" location="classpath:jeesite.properties"/>
二、在spring.xml 中使用配置文件属性:code
<property name="username" value="#{util_Spring['jdbc.username']}" /> <property name="password" value="#{util_Spring['jdbc.password']}" />
三、在java文件中使用:xml
@Value(value="#{util_Spring['UTIL_SERVICE_ONE']}") private String UTIL_SERVICE_ONE;
3、经过 @PropertySource 注解实现配置文件加载
一、用法示例:在java类文件中使用 PropertySource 注解:ip
@PropertySource(value={"classpath:redis-key.properties"}) public class ReadProperties { @Value(value="${jdbc.username}") private String USER_NAME; }
二、在java文件中使用:get
@Value(value="${jdbc.username}") private String USER_NAME;
4、经过 PropertyPlaceholderConfigurer 类读取配置文件
一、用法示例:在 spring.xml 中使用 <bean>标签进行配置
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:redis-key.properties</value> </list> </property> </bean>
二、 PropertyPlaceholderConfigurer 配置方法,等价于 方式一,用法参考方法一。
<!-- 基本属性 url、user、password --> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" />