java spring Bean Autowiring 自动依赖装配

除了在Bean定义文件中直接指定字符串值,使用<ref>直接指定参考至其他的Bean,或是使用<bean>标签并指定"class"属性来指定依赖对象之外,spring也支持隐式的自动绑定,您可以透过类型(byType)或名称(byName)将某个Bean实例绑定至其他Bean对应的属性,比如
<bean id="helloBean" class="....." autowire="byType">
...
</bean>


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>

    <bean id="triangle" name="triangle-name" class="zxl.Triangle" autowire="byName" >

    </bean>

    <bean id="pointA" class="zxl.Point" >
        <property name="x" value="0" />
        <property name="y" value="0" />
    </bean>

    <bean id="pointB" class="zxl.Point" >
        <property name="x" value="-20" />
        <property name="y" value="0" />
    </bean>

    <bean id="pointC" class="zxl.Point" >
        <property name="x" value="20" />
        <property name="y" value="0" />
    </bean>

</beans>

package zxl;

import java.util.List;


public class Triangle {
	
	private Point pointA;
	private Point pointB;
	private Point pointC;
	
	public Point getPointA() {
		return pointA;
	}

	public void setPointA(Point pointA) {
		this.pointA = pointA;
	}

	public Point getPointB() {
		return pointB;
	}

	public void setPointB(Point pointB) {
		this.pointB = pointB;
	}

	public Point getPointC() {
		return pointC;
	}

	public void setPointC(Point pointC) {
		this.pointC = pointC;
	}


	
	public void draw(){
		
		System.out.println("point A ("+getPointA().getX()+","+getPointA().getY()+")");
		System.out.println("point B ("+getPointB().getX()+","+getPointB().getY()+")");
		System.out.println("point C ("+getPointC().getX()+","+getPointC().getY()+")");
		
	}
}

package zxl;

public class Point {
	private int x;
	private int y;
	
	public int getX() {
		return x;
	}
	public void setX(int x) {
		this.x = x;
	}
	public int getY() {
		return y;
	}
	public void setY(int y) {
		this.y = y;
	}
	
}

package zxl;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DrawingApp {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
		Triangle triangle =(Triangle) context.getBean("triangle");
		triangle.draw();
	}

}













你可能感兴趣的:(java spring Bean Autowiring 自动依赖装配)