Spring多配置文件
-
多配置文件的优势:
每个文件的大小比一个文件要小很多,效率变高
分成多模块,减少冲突
创建俩个类
public class School {
private String name;
private String address;
public School(String name, String address) {
this.name = name;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
'}';
}
}
public class Student {
private School school;
private String name;
private int age;
public School getSchool() {
return school;
}
public void setSchool(School school) {
this.school = school;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "School{" +
"school=" + school +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
编写xml文件,将xml文件分成三部分,第一部分是写school,第二部分是student,最后一部分是汇总
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="school" class="spring.ba04_多配置文件.School">
<constructor-arg value="北京"/>
<constructor-arg value="北大"/>
</bean>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="student" class="spring.ba04_多配置文件.Student" autowire="byName">
<property name="name" value="张三"/>
<property name="age" value="20"/>
</bean>
</beans>
汇总,放的是绝对路径
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:ba04/spring-student.xml"/>
<import resource="classpath:ba04/spring-school.xml"/>
</beans>
如果汇总一个个写的话,太费事,所以我们可以使用通配符来写入,但是使用通配符要记住俩点。第一:不能自己本身写入,第二几个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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:ba04/spring-s*.xml"/>
</beans>