spring之加载属性配置文件
先定义属性配置文件,在resources文件夹下创建test.properties:
myname=hk
myage=18
然后在applicationContext.xml核心文件中定义标签去加载这个配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--
声明组件扫描器(component-scan),组件就是java对象
base-package:指定注解在你的项目中的包名。
component-scan工作方式: spring会扫描历base-package指定的包,
把包中和子包中的所有类,找到类中的注解,按照注解的功能创建对象,或给属性属值。
加入了component-scan标签,配置文件的变化:
1.加入一个新的约束文件spring-context.xsd
2.给这个新的约束文件起个命名空间的名称
-->
<context:component-scan base-package="com.apps.pojo07" />
<!-- 加载属性配置文件,classpath:表示类路径 -->
<context:property-placeholder location="classpath:test.properties" />
</beans>
然后就可以在java类中使用 ${} 来获取test.properties属性文件中的值, ${} 中的内容为properties属性文件中的key值
package com.apps.pojo07;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* @author hk Email:2113438464@qq.com
* @ClassName Student
* @Description : 实体类
* @date 2021/6/7
*/
//省略value
@Component("myStudent")
public class Student {
/**
* @Value: 简单类型的属性赋值
*/
@Value("${myname}")
private String name;
@Value("${myage}")
private Integer age;
//使用byName
@Resource(name = "mySchool")
private School school;
public Student() {
}
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
System.out.println("setAge:"+age);
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", school=" + school +
'}';
}
}