Spring commonly used two kinds of dependency injection method: One is to set the value injection method, the bean's setter method sets the Bean attribute value, the other is the construction injection, by giving the bean's construction method to pass the parameters to implement the Bean attribute assignment value;
1. Set Value injection mode
Directly on the code example, the tree structure of the example is shown below
Shape.java interface Content
Package Chapter3; Public Interface Shape { publicdouble area (); Find the area of the shape }
Circle.java content:
Package Chapter3; Public classCircle implements Shape {DoubleR; Public DoubleGetr () {return This. R; } Public voidSETR (DoubleR) { This. r=R; } @Override Public DoubleArea () {//TODO auto-generated Method Stub returnMath.pi*math.pow (R,2); }}
Rectangle.java Content
Package Chapter3; Public classRectangle implements Shape {DoubleWidth,height; Public Doublegetwidth () {return This. Width; } Public voidSetWidth (Doublewidth) { This. width=width; } Public Doublegetheight () {return This. Height; } Public voidSetHeight (Doubleheight) { This. height=height; } @Override Public DoubleArea () {//TODO auto-generated Method Stub returnwidth*height; }}
Anyshape.java Content
Package Chapter3; Public class anyshape { shape shape; Public void setshape (shape shape) {this. shape=shape;} Public Shape Getshape () {returnthis. Shape;} Public void Outputarea () { System. out. println (" area ="+Shape.area ());} }
Test.java Content
Package Chapter3;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.*; Public classTest {/** * @param args*/ Public Static voidMain (string[] args) {//TODO auto-generated Method StubApplicationContext context=NewFilesystemxmlapplicationcontext ("Src/mycontext.xml"); Anyshape Shape= (Anyshape) Context.getbean ("Anyshape"); Shape.outputarea (); Anyshape Shape2= (Anyshape) Context.getbean ("anyShape2"); Shape2.outputarea (); }}
XML configuration file
<?xml version="1.0"encoding="UTF-8"? ><beans xmlns="Http://www.springframework.org/schema/beans"Xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation="Http://www.springframework.org/schema/beanshttp//www.springframework.org/schema/beans/spring-beans-2.5.xsd "><bean id="MyShape" class="Chapter3. Circle"> <property name="R"> <value>2.5</value> </property> </bean> <bean id="myShape2" class="Chapter3. Rectangle"> <property name="Height"> <value>2</value> </property> <property name="width"> <value>5</value> </property> </bean> <bean id="Anyshape" class="Chapter3. Anyshape"> <property name="Shape"> <refbean="MyShape"/> </property> </bean> <bean id="anyShape2" class="Chapter3. Anyshape"> <property name="Shape"> <refbean="myShape2"/> </property> </bean></beans>
Java Spring Learning Note----Bean Dependency Injection (1)