bean的继承和依赖 spring除了提供了一般的配置bean的方式之外,还实现了java中继承的特性,设置bean的父子关系,这样对于一些重复的配置就可以进行省略
bean的继承 配置bean的父子关系,父bean有的东西,子bean全部继承过来,不一样的进行覆盖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <bean id ="parent" class ="com.zhanghe.study.spring4.beans.beantest.Person" > <property name ="name" value ="张三" /> <property name ="car" ref ="car" /> <property name ="cars" > <list > <ref bean ="car" /> <ref bean ="car2" /> </list > </property > <property name ="carMap" > <map > <entry key ="AA" value-ref ="car" /> <entry key ="BB" value-ref ="car2" /> </map > </property > </bean > <bean id ="son" parent ="person" > <property name ="name" value ="张飞" /> </bean >
抽象bean 既然spring提供了继承,那么也就存在了专门用于被继承的bean,而不进行实例化,这种bean被称为抽象bean,使用abstract=”true”表明这是一个抽象bean
由于抽象bean不进行实例化,所以抽象bean的class属性是没有意义的,可以省略不写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <bean id ="abstract" abstract ="true" > <property name ="name" value ="张三" /> <property name ="car" ref ="car" /> <property name ="cars" > <list > <ref bean ="car" /> <ref bean ="car2" /> </list > </property > <property name ="carMap" > <map > <entry key ="AA" value-ref ="car" /> <entry key ="BB" value-ref ="car2" /> </map > </property > </bean > <bean id ="personSon" class ="com.zhanghe.study.spring4.beans.beantest.Person" parent ="abstract" > <property name ="name" value ="张飞" /> </bean >
注意:抽象bean是不可以被实例化的,也就是说不可以使用上下文强制的获取该bean,否则会报错
org.springframework.beans.factory.BeanIsAbstractException: Error creating bean with name ‘abstract’: Bean definition is abstract
bean的依赖 有时候需要保证bean实例化的先后顺序,在创建一个bean的时候必须保证另外一个bean也被创建,如果另一个bean不存在,则无法正常实例化该bean
可以使用depends-on来实现bean之间的依赖关系
1 2 3 4 5 6 7 8 <bean id ="person2" class ="com.zhanghe.study.spring4.beans.beantest.Person" parent ="abstract" depends-on ="depend1" > <property name ="name" value ="关羽" /> </bean > <bean id ="depend1" class ="com.zhanghe.study.spring4.beans.beantest.Person" parent ="abstract" > <property name ="name" value ="刘备" /> </bean >
如果所依赖的bean不存在,实例化失败
警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘person2’ defined in class path resource [spring-config.xml]: ‘person2’ depends on missing bean ‘depend1’; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘depend1’ available