There are two commonly used dependency injection methods in Spring: one is the set-value injection method, which uses the bean's setter method to set the property value of the bean; the other is the construction injection, which implements the assignment of the bean's properties by passing parameters to the bean's construction method;
1. Set value injection method
Go directly to the code example, the tree structure diagram of the example is as follows
Shape.java interface content
package chapter3; public interface Shape { public double area(); // Find the area of the shape }
Circle.java content:
package chapter3; public class Circle implements Shape { double r; public double getR(){ return this.r; } public void setR(double r){ this.r=r; } @Override public double area() { // TODO Auto-generated method stub return Math.PI*Math.pow(r, 2); } }
Rectangle.java content
package chapter3; public class Rectangle implements Shape { double width,height; public double getWidth(){ return this.width; } public void setWidth(double width){ this.width=width; } public double getHeight(){ return this.height; } public void setHeight(double height){ this.height=height; } @Override public double area() { // TODO Auto-generated method stub return width*height; } }
AnyShape.java content
package chapter3; public class AnyShape { Shape shape; public void setShape(Shape shape) {this.shape=shape;} public Shape getShape(){return this.shape;} public void outputArea(){ System.out.println("面积="+shape.area()); } }
Test.java content
package chapter3; import org.springframework.context.ApplicationContext; import org.springframework.context.support.*; public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext context=new FileSystemXmlApplicationContext("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/beans http://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"> <ref bean="myShape"/> </property> </bean> <bean id="anyShape2" class="chapter3.AnyShape"> <property name="shape"> <ref bean="myShape2"/> </property> </bean> </beans>