Spring&Spring MVC技术分享-DI:Bean的继承
作者:
22-426
,
2022-03-24 17:28:42
,
所有人可见
,
阅读 172
C02_D12_bean_inheritance
//bean
public class Address {
private String province; //省
private String city; //市
private String detailedAddress; //详细地址
@Override
public String toString() {
return "地址::" + province + "省" + city + "市" + detailedAddress;
}
public void setProvince(String province) {
this.province = province;
}
public void setCity(String city) {
this.city = city;
}
public void setDetailedAddress(String detailedAddress) {
this.detailedAddress = detailedAddress;
}
}
public class Employee {
private String empId; // 员工编号
private String empName; // 员工姓名
private double empSalary; // 员工工资
private Address address; // 员工地址
public void init() {
System.out.println("init....");
}
public void destroy() {
System.out.println("destroy....");
}
public void showEmployeeDetails() {
System.out.println("---------------员工信息---------------");
// 输出员工基本信息
System.out.println("工号:" + empId);
System.out.println("姓名:" + empName);
System.out.println("工资:" + empSalary);
// 输出员工地址信息
System.out.println(address);
}
public void setEmpId(String empId) {
this.empId = empId;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public void setEmpSalary(double empSalary) {
this.empSalary = empSalary;
}
public void setAddress(Address address) {
this.address = address;
}
}
//config-beans.xml
<bean id="addr1" class="com.qdu.bean.Address">
<property name="province" value="山东" />
<property name="city" value="青岛" />
<property name="detailedAddress" value="宁夏路308号 青岛大学" />
</bean>
<bean id="addr2" class="com.qdu.bean.Address">
<property name="province" value="山东" />
<property name="city" value="临沂" />
<property name="detailedAddress" value="人民广场" />
</bean>
<bean id="emp1" class="com.qdu.bean.Employee" init-method="init"
destroy-method="destroy">
<property name="empId" value="E001" />
<property name="empName" value="小明" />
<property name="empSalary" value="20000.3" />
<property name="address" ref="addr1" />
</bean>
<!-- 可以使用bean标记的parent属性指定当前bean继承自哪个bean -->
<!-- 给出其id或name即可 -->
<!-- bean的继承类似类的继承,但不是类的继承 -->
<!-- 而是继承那个bean的配置,包括依赖注入和特定于容器的配置(范围、init-method等) -->
<!-- 方便重用代码 -->
<!-- 如果在当前bean定义了相同的依赖注入或配置,则覆盖继承的配置 -->
<bean id="emp2" class="com.qdu.bean.Employee" parent="emp1">
<property name="address" ref="addr2" />
</bean>
//main
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("config/beans.xml");
Employee emp1 = (Employee) ctx.getBean("emp1");
emp1.showEmployeeDetails();
Employee emp2 = (Employee) ctx.getBean("emp2");
emp2.showEmployeeDetails();
((ClassPathXmlApplicationContext)ctx).registerShutdownHook();
}