spring配置bean的细节二

来源:互联网 发布:练六级英语听力的软件 编辑:程序博客网 时间:2024/06/09 01:06
一 内部bean
<bean id="foo" class="....Foo">
    <property name=”属性”>
    <!—第一方法引用-->
    <ref bean='bean对象名'/>
    <!—内部bean-->
    <bean>
    <properyt></property>
</bean>
</property>
</bean>
这种方式的缺点是你无法在其它地方重用这个bar实例,原因是它是专门为foo而用。

二 继承配置
1、继承
2、继承配置
3、覆盖父 Bean配置
4、可以设置 <bean> 的abstract 属性为 true, Spring 不会实例化该Bean

三 代码
1 Student
package com.hsp.inherit;public class Student {                protected String name;        protected int age;        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;        }}

2 Gradate
package com.hsp.inherit;public class Gradate extends Student {        private String degree;        public String getDegree() {                return degree;        }        public void setDegree(String degree) {                this.degree = degree;        }        }

3 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";                xmlns:context="http://www.springframework.org/schema/context";                xmlns:tx="http://www.springframework.org/schema/tx";                xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-2.5.xsd";><!-- 配置一个学生对象 --><bean id="student" class="com.hsp.inherit.Student">        <property name="name" value="顺平" />        <property name="age" value="30"/></bean><!-- 配置Grdate对象 --><bean id="grdate" parent="student" class="com.hsp.inherit.Gradate">        <!-- 如果自己配置属性name,age,则会替换从父对象继承的数据  -->        <property name="name" value="小明"/>        <property name="degree" value="学士"/></bean></beans>

4 App1
package com.hsp.inherit;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class App1 {    /**     * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub        ApplicationContext ac=new ClassPathXmlApplicationContext("com/hsp/inherit/beans.xml");            Gradate gradate=(Gradate) ac.getBean("grdate");        System.out.println(gradate.getName()+" "+gradate.getAge()+" "+gradate.getDegree());    }}

四 测试结果
小明 30 学士
原创粉丝点击