Spring_Bean 之间的关系
beans-relation.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--
<bean id="address" class="com.hy.spring.beans.autowire.Address"
p:city="BeiJing^" p:street="HuiLongGun">
</bean>
-->
<!--
抽象bean: bean的 abstract属性为true的bean. 这样的bean不能被IOC 容器实例化,只能被继承配置
若某一个bean的class 属性没有指定,则该bean必须是一个抽象的bean
-->
<bean id="address" p:city="BeiJing^" p:street="HuiLongGun" abstract="true">
</bean>
<bean id="address1" class="com.hy.spring.beans.autowire.Address"
p:city="BeiJing" p:street="WuDaoKou" parent="address">
</bean>
</beans>
Main.java
package com.hy.spring.beans.relation;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.hy.spring.beans.autowire.Address;
public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-relation.xml");
//Address address = (Address) ctx.getBean("address");
//System.out.println(address);
Address address = (Address) ctx.getBean("address1");
System.out.println(address);
}
}
XML 配置
<bean id="car" class="com.hy.spring.beans.autowire.Car"
p:brand="Audi" p:price="300000">
</bean>
<!--
要求再配置person时,必须有一个关联的car!
换句话说person 这个bean 依赖于Car 这个bean
-->
<bean id="person" class="com.hy.spring.beans.autowire.Person"
p:name="Tom" p:address-ref="address1" depends-on="car">
</bean>