春天与bean的关系是什么

  介绍

这篇文章给大家介绍弹簧与bean的关系是什么,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

<强>一、继承关系

地址。java

package  com.gong.spring.beans.autowire;      public  class  Address  {   private 才能;String 城市;   private 才能;String 街;   ,,   public 才能;String  getCity (), {   ,,,return 城市;   ,,}      public 才能;void  setCity (String 城市),{   ,,,this.city =,城市;   ,,}      public 才能;String  getStreet (), {   ,,,return 街;   ,,}      public 才能;void  setStreet (String 街),{   ,,,this.street =,街;   ,,}      @Override才能   public 才能;String  toString (), {   ,,,return “Address [城市=?+,city  +,,,,街道=?+,street  +,“]”;   ,,}   }

beans-relation。xml

& lt; ? xml  version=?.0“,编码=癠TF-8" ?比;   http://www.springframework.org/schema/beans" & lt; beans  xmlns=?;   ,,xmlns: xsi=癶ttp://www.w3.org/2001/XMLSchema-instance"   xmlns:才能p=癶ttp://www.springframework.org/schema/p"   ,,xsi: schemaLocation=? http://www.springframework.org/schema/beans , http://www.springframework.org/schema/beans/spring-beans.xsd"比;   & lt;才能bean  id=癮ddress",类=癱om.gong.spring.beans.autowire.Address",   p:才能城市=拔浜骸?p:街道=奥缒辖值馈白4? lt;/bean>   & lt; !——,才能使用父母指定指定哪个bean的配置,子bean可以覆盖父bean的配置,——比;   & lt;才能bean  id=癮ddress2",类=癱om.gong.spring.beans.autowire.Address",父母=癮ddress",   p:才能街=扮笫ń值馈白4? lt;/bean>   & lt;/beans>

主要。java

package  com.gong.spring.beans.autowire;      import  org.springframework.context.ApplicationContext;   import  org.springframework.context.support.ClassPathXmlApplicationContext;      public  class  Main  {   public 才能;static  void  main (String [], args), {   ,,,//1。创建spring的IOC容器对象   ,,,ApplicationContext  ctx =, new  ClassPathXmlApplicationContext (“beans-relation.xml");   ,,,//2。从容器中获取豆实例   ,,,Address  Address =,(地址),ctx.getBean (“address");,   ,,,System.out.println (address.toString ());   ,,,Address  address2 =,(地址),ctx.getBean (“address2");,   ,,,System.out.println (address2.toString ());   ,,}   }

输出:

春天与bean的关系是什么

address2继承了地址的城市配置,因此城市=武汉。

当然,我们也可以使用抽象来表明一个bean是一个抽象bean。抽象bean可以作为一个模板,且不能被实例化。同时,如果一个bean没有声明,那么也该bean是一个抽象bean,且必须指定文摘=皌rue"。

& lt; bean  id=癮ddress",类=癱om.gong.spring.beans.autowire.Address",文摘=皌rue"   p:才能城市=拔浜骸?p:街道=奥缒辖值馈白4? lt;/bean>

此时,在进行实例化就会报错

Address  Address =,(地址),ctx.getBean (“address");

春天与bean的关系是什么

将抽象豆作为父bean可以实例化它的子豆:

,, Address  address2 =,(地址),ctx.getBean (“address2");,   System.out.println才能(address2.toString ());

春天与bean的关系是什么

<强>二、依赖关系

汽车。java

package  com.gong.spring.beans.autowire;      public  class  Car  {   ,,   public 才能;汽车(),{   ,,}      public 才能;汽车(String 名称),{   ,,,this.name =,名称;   ,,}   private 才能;String 名称;      public 才能;String  getName (), {   ,,,return 名称;   ,,}      public 才能;void  setName (String 名称),{   ,,,this.name =,名称;   ,,}      @Override才能   public 才能;String  toString (), {   ,,,return “Car  [name=? +, name  +,“]”;   ,,}   ,,   }

春天与bean的关系是什么