One inheritance
The inheritance relationship between multiple beans in spring, similar to the inheritance relationship in object-oriented, looks directly at the code.
Define a person class first
Packagecom.demo.spring.entity;/** * @authorChenyk * @date June 15, 2018*/ Public classPerson {PrivateString name; PrivateString address; PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } PublicString getaddress () {returnaddress; } Public voidsetaddress (String address) { This. Address =address; } }
Then configure it in the Beans.xml file:
<BeanID= "Person"class= "Com.demo.spring.entity.Person"p:address= "Hangzhou"Abstract= "true"> </Bean> <BeanID= "Person2"P:name= "John Doe"Parent= "Person"> </Bean>
In Beans.xml, we define an abstract class named person, which, as a parent class, encapsulates a common attribute value address= "Hangzhou", because it defines abstract= "true", so it cannot be instantiated. It then defines a class named Person2, which inherits the person.
Get Person2 Object
@Test Public voidtestbeanfactory () {Classpathresource resource=NewClasspathresource ("Beans.xml");//Locate the resource file and parse the bean into beandefinition.Defaultlistablebeanfactory beanfactory =Newdefaultlistablebeanfactory (); Xmlbeandefinitionreader Reader=NewXmlbeandefinitionreader (beanfactory); Reader.loadbeandefinitions (Resource); //loading beandefinition into the containerPerson Person2 = (person) beanfactory.getbean ("Person2"); System.out.println ("Name=" +person2.getname () + "; address=" +person2.getaddress ()); }
Operation Result: Name= John Doe; address= Hangzhou
Two-dependency: using depends-on to implement dependencies
Define a person class
Packagecom.demo.spring.entity;/** * @authorChenyk * @date June 15, 2018*/ Public classPerson {PrivateString name; PrivateString address; PrivateAir Air; PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } PublicString getaddress () {returnaddress; } Public voidsetaddress (String address) { This. Address =address; } PublicAir Getair () {returnAir; } Public voidSetair (air air) { This. Air =Air; }}
Defining the Air class
Package com.demo.spring.entity; /** @author*/Publicclass Air {}
Configuring in Beans.xml
<BeanID= "Person"class= "Com.demo.spring.entity.Person"P:name= "Zhang San"p:address= "Hangzhou"Abstract= "true"> </Bean> <BeanID= "Person2"P:name= "John Doe"Parent= "Person"depends-on= "Air"> </Bean> <BeanID= "Air"class= "Com.demo.spring.entity.Air"> </Bean>
Depends-on a dependency is set on the tag, the Person2 property air must be present or an error is made, and if there is no depends-on tag, the default Person2 property air is null.
Three injections:
Injection, we can also be called Dependency injection, injected in three ways: Setter method injection, constructor injection, annotated way to inject. This is not explained in detail here.
Relationships between spring beans: inheritance, dependency, dependency injection