Spring学习笔记之Bean定义继承

本文介绍如何在Spring框架中使用Bean定义继承简化配置,通过抽象Bean减少重复配置,并展示具体的XML配置示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

若Bean定义文件内容很多,而且部分Bean的定义有重复,如属性相同,只有几个Bean有不同 的设置,则可以考虑继承某个Bean定义,好处多多:

People类

package com.nalis.spring;

public class People {
    
private String name;

    
private int age;

    
public int getAge() {
        
return age;
    }


    
public void setAge(int age) {
        
this.age = age;
    }


    
public String getName() {
        
return name;
    }


    
public void setName(String name) {
        
this.name = name;
    }

}

src目录下的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-2.0.xsd">
    
<bean id="inheritedPeople" abstract="true">
        
<property name="name" value="guest" />
        
<property name="age" value="18" />
    
</bean>
    
<bean id="temp1" class="com.nalis.spring.People"
        parent
="inheritedPeople">
        
<property name="name" value="nalis" />
        
<property name="age" value="24" />
    
</bean>
</beans>

测试类:BeaninheritedDemo

 

package com.nalis.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeaninheritedDemo {


    
public static void main(String[] args) {
        
// TODO Auto-generated method stub
        ApplicationContext context = new ClassPathXmlApplicationContext(
                
"beans.xml");
        People people 
= (People) context.getBean("temp1");
        System.out.println(
"name: " + people.getName());
        System.out.println(
"age: " + people.getAge());
    }


}

此上是完全抽象的Bean定义继承,还可以从一个Bean实例的定义中继承

<bean id="people" class="com.nalis.spring.People">
        
<property name="name" value="zhang3" />
        
<property name="age" value="44" />
</bean>

<bean id="temp2" class="com.nalis.spring.People"    parent="people">
        
<property name="name" value="li4" />
        

</bean>

此例"people"已经实例化,若有必要,可用其他Bean(如"temp2")继承其定义.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值