Spring学习笔记

Spring依赖注入(控制反转.)
  依赖注入是Spring的核心机制,可以使Spring的Bean以配置文件组织在一起,而不是以硬编码的方式耦合在一起.
所谓依赖注入,是指在程序运行过程中,如果需要调用另一个对象协助时,无须在代码中创建被调用者,而是依赖于外部的注入.Spring的依赖注入对调用者和别调用者几乎没有任何要求,完全支持对POJO之间依赖关系的管理.



依赖注入通常有两种:

1 设值注入 :是通过setter方法传入被调用者的实例,这中方式注入简单,直观

设值注入例程:

Person接口:
package org.yaoyuan.Spring;

public interface Person {
	
		public void useAxe();
}

Axe接口:
package org.yaoyuan.Spring;

public interface Axe {
	
	public String chop();
}

Person的实现类Chinese:
package org.yaoyuan.Spring;

public class Chinese implements Person{

	private Axe axe;
	
	public Chinese(){
		
	}
	
	public void setAxe(Axe axe){
		this.axe = axe;
	}
	
	public void useAxe(){
		System.out.println(axe.chop());
	}

}


Axe实现类StoneAxe:
package org.yaoyuan.Spring;

public class StoneAxe implements Axe{

	public StoneAxe(){
		
	}
	
	public String chop() {

			return "石斧头砍材好瞒";
	}

}

Spring的配置文件:
<?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/b	2.0.xsd">

	<bean id="chinese" class="org.yaoyuan.Spring.Chinese">
		<property name="axe">
			<ref local="stoneAxe"/>
		</property>
	</bean>
	<beanid="stoneAxe"class="org.yaoyuan.Spring.StoneAxe">
</bean>
</beans>

测试类BeanTest:
package org.yaoyuan.Spring;

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

public class BeanTest {
	public static void main(String[] args){
		ApplicationContext ctx = new ClassPathXmlApplicationContext("org/yaoyuan/Spring/applicationContext.xml");
		Person p = (Person)ctx.getBean("chinese");
		p.useAxe();
	}
}


测试结果:
石斧头砍材好瞒



2 构造注入:指通过构造函数来完成依赖关系的设定,而不是通过setter方法.

对Chinese修改:
Public class Chinese implements Person
{
Private Axe axe;
public Chinese()
{
}

public Chinese(Axe axe)
{
this.axe = axe;
} 

public void userAxe()
{
System.out.println(axe.chop());
}
}


对配置文件修改:

<?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/b	2.0.xsd">

	<bean id="chinese" class="org.yaoyuan.Spring.Chinese">
		<construction-arg>
<ref bean="steelAxe" />
</construction-arg>
	</bean>
	<beanid="stoneAxe"class="org.yaoyuan.Spring.StoneAxe">
</bean>
</beans>



两种注入方式的优点:

设值注入的优点:

  1.设值注入与传统的JavaBean的写法更相似,程序开发人员更容易了 解, 接受.通过setter方法设定依赖关系显得更加直观,自然.
  2.对于复杂的依赖关系,如果采用构造注入,会导致构造器过于臃肿,难 以 阅读.因为Spring在创建bean实例时,需要同时实例化其依赖的全部 实例,因而导致性能下降.
      3.尤其是在某些属性可选的情况下,多参数的构造器更加笨重.

构造注入的优点:

  1.可以在构造器中决定依赖关系的注入顺序
  2.对于依赖关系无须改变的bean,构造注入更有用处,因为没setter方法, 所有的依赖关系全部在构造器内设定,因此,无须担忧后续的代码对依 赖关系产生破坏
  3.依赖关系只能在构造器中设定,因为只有组件的创建者才能改变组件的 依赖关系,对于组件的调用者而言,组件的内部的依赖关系完全透明,更 符合高内聚的原则.

你可能感兴趣的:(java,spring,bean,xml,配置管理)