abstract的应用是怎么回事呢?
比如,有个学生类和员工类,都有名字和年龄字段
public class Employee {
private String name;
private Integer age;
private String compony;
public Employee() {
}
public Employee(String name, Integer age, String compony) {
this.name = name;
this.age = age;
this.compony = compony;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getCompony() {
return compony;
}
public void setCompony(String compony) {
this.compony = compony;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", age=" + age +
", compony='" + compony + '\'' +
'}';
}
}
public class Student {
private String name;
private Integer age;
private String school;
public Student(String name, Integer age, String school) {
this.name = name;
this.age = age;
this.school = school;
}
public Student() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", school='" + school + '\'' +
'}';
}
}
我们可以抽取相同的字段,做成一个父配置,就叫模板吧更形象
<?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="template" abstract="true">
<property name="name" value="Apollo"/>
<property name="age" value="20"/>
</bean>
<bean id="student" class="fun.gosuncn.spring01.Student" parent="template">
<property name="school" value="北京大学"/>
</bean>
<bean id="employee" class="fun.gosuncn.spring01.Employee" parent="template">
<property name="compony" value="小米科技有限公司"/>
</bean>
</beans>
测试运行
public class TestMain {
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring01.xml");
Object student = applicationContext.getBean("student");
System.out.println("student = " + student);
Object employee = applicationContext.getBean("employee");
System.out.println("employee = " + employee);
}
}
结果:
student = Student{name=‘Apollo’, age=20, school=‘北京大学’}
employee = Employee{name=‘Apollo’, age=20, compony=‘小米科技有限公司’}
文章到此就结束了,拜拜!