用spring 配置文件 读取properties文件
Spring提供了读取外部properties文件的机制,使用读取到的数据为bean的属性赋值
操作步骤
1,准备外部properties文件
2,开启context命名空间支持
xmlns: context="http://ww. sprinaframework.ora/schema/context"
3,加哦指定的properties文件
<context:property-placeholder location="classpath: filename.properties">
4,使用加载的数据
<property nane="propertyName" value="$(propertiesName)"/>
注意:如果需要加载所有的properties文件,可以使用*.properties表示加载所有的properties文件
注意:读取数据使用$ (propertiesName)格式进行,其中propertiesName指properties文件中的属性名
data.properties配置文件
username=root
pwd=123321
dao层实现类
public class UserDaoImpl implements UserDao{
private String userName;
private String password;
public void setUserName(String userName) {
this.userName = userName;
}
public void setPassword(String password) {
this.password = password;
}
//这样是为了在控制台显示这两个成员接受到的值
public void save(){
System.out.println("user dao running..."+userName+" "+password);
}
}
、 private String userName;
private String password;
这是对properties文件key的值,目的是用来接受从spring配置文件中过来的properties的key的值
用这个方法要写出这两个成员的set方法
spring配置文件application
开启context命名空间支持 才能使用context标签中的属性
xmlns:context="http://www.springframework.org/schema/context"
<!--2.加载配置文件-->
<context:property-placeholder location="classpath:*.properties"/>
location 这是定位,就是锁定文件的路径位置
location="classpath:*.properties 这是在引入properties文件
classpath 字节码路径的意思
这是在bean里面注入data.properties配置文件key的名称
value="${username} 就是指向data.properties配置文件的 username获取他的值 root
name="userName"这是给它配置的名称,与代码对象的成员名称一致,就建立起它与成员之间的对应关系
<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl">
<property name="userName" value="${username}"/>
<property name="password" value="${pwd}"/>
</bean>
这是将BookDaoImpl注入到bean容器中,给他设置一个id值,方便以后通过这个id值找到这个类来操作
<bean id="bookDao" class="com.itheima.dao.impl.BookDaoImpl"/>
这是对应service层实现类中的dao成员name=“userDao”
ref=“userDao” 这是在本配置文件中注入的dao实体类的id值
<bean id="userService" class="com.itheima.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"/>
<property name="bookDao" ref="bookDao"/>
</bean>
这是spring配置文件头
意思是把前面两行都复制到下面
将前面两行中 bean这个名称都换成 context
这是在加入context标签
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd"
${} 这是用来获取properties文件中的信息的
#{} 这是sple表达式