Spring学习(五)-Spring与Bean的关系

来源:互联网 发布:追求卓越 知乎 编辑:程序博客网 时间:2024/05/18 01:17

Spring与bean的关系总结:
1)使用autowire 自动装载:
可以使用autowire属性自动装载,byName根据bean的名字的setXx风格的属性名自动装配,有的自动装配,没有的不装配 byType根据bean的类型和当前bean的属性的类型自动装配,若IOC容器中有一个以上的类型匹配的bean,则匹配异常
缺点:要装配必须属性全装配,再者装配方式只能用一种
2)抽象bean:
bean:bean的abstract属性为true的bean 这样的bean不能被IOC容器实例化,
只能用来被继承 配置,若某一个bean的class属性没有指定,则该bean必须是一个抽象bean
3)bean配置的继承:
使用bean的parent属性指定继承那个bean的属性
4)关联bean:
要求配置Person时 必须有一个关联的car换句话说person这个bean依赖于Car的这个bean

1.bean2.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:util="http://www.springframework.org/schema/util"xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsdhttp://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"><bean id="address" class="com.autowire.bean.Address"    p:city="Beijing" p:street="HuiLongGuan">    </bean><bean id="car" class="com.autowire.bean.Car"    p:brand="Audi" p:price="300000"></bean><!-- 可以使用autowire属性自动装载,    byName根据bean的名字的setXx风格的属性名自动装配,有的自动装配,没有的不装配     byType根据bean的类型和当前bean的属性的类型自动装配,若IOC容器中有一个以上的类型匹配的bean,则匹配异常    缺点:要装配必须属性全装配,再者装配方式只能用一种--><!--抽象bean:bean的abstract属性为true的bean 这样的bean不能被IOC容器实例化,    只能用来被继承 配置,若某一个bean的class属性没有指定,则该bean必须是一个抽象bean--><bean id="person" class="com.autowire.bean.Person"    p:name="Tom" p:address-ref="address" p:car-ref="car" abstract="true" >    <!--  autowire="byName"-->    <!--  p:address-ref="address" p:car-ref="car"--></bean><!-- bean配置的继承:使用bean的parent属性指定继承那个bean的属性 --><bean id="person2" class="com.autowire.bean.Person"    p:name="Rose" parent="person"></bean><!-- 要求配置Person时 必须有一个关联的car换句话说person这个bean依赖于Car的这个bean --><bean id="person3" class="com.autowire.bean.Person"    p:name="Jack" p:address-ref="address" depends-on="car"></bean</beans>

2.TestAutowire.java测试类

package com.autowire.bean;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestAutowire {    public static void main(String[] args) {        @SuppressWarnings("resource")        ApplicationContext ctx=new                 ClassPathXmlApplicationContext("springXML/bean2.xml");        /*Person person=(Person)ctx.getBean("person");        System.out.println(person);        */        Person person2=(Person)ctx.getBean("person2");        System.out.println(person2);        Person person3=(Person)ctx.getBean("person3");        System.out.println(person3);    }}
原创粉丝点击