程序概念:
Spring容器管理容器中Bean之间的依赖关系,Spring使用一种被称为“依赖注入”的方式来管理Bean之间的依赖关系。使用依赖注入,不仅可以为Bean注入普通的属性值,还可以注入其他Bean的引用。依赖注入是一种优秀的解耦方式,其可以让Bean以配置文件组织在一起,而不是以硬编码的方式耦合在一起。
依赖注入分为两种:
1:set注入
2:构造注入
示例:set注入
public class Axe {
public void chop(){
System.out.println("用斧头砍树");
}
}
public class Person {
private Axe axe;
//set注入axe
public void setAxe(Axe axe) {
this.axe = axe;
}
public void UseAxe(){
System.out.println("上山砍树");
axe.chop();
}
}
//ApplicationContext是Spring容器最常用的接口,该接口有如下两个实现类:
1)ClassPathXmlApplicationContext:
从类加载路径下搜索配置文件,并根据配置文件来创建Spring容器。
2)FileSystemXmlApplicationContext:
从文件系统的相对路径或绝对路径下去搜索配置文件,并根据配置文件来创建Spring容器。
public class PersonMannager {
public static void main(String[] args) {
ApplicationContext aContext=new ClassPathXmlApplicationContext("bean.xml");
aContext.getBean("axe", Person.class).UseAxe();
构造注入:(多写一个chinese类)
public class Chinexe implements Person {
private Axe axe;
//需要构造注入的内容
public Chinexe(Axe axe) {
this.axe=axe;
}
@Override
public void useAxe() {
System.out.println("中国人用");
axe.chop();
}
}
构造注入的配置文件xml:(beans后面为根元素,在spring-framework-4.0.4.RELEASE\schema可以找到)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<bean id="chinese1" class="com.cn.domain.impl.Chinexe">
<constructor-arg name="axe" ref="steelAxe"></constructor-arg>
</bean>
<bean id="chinese2" class="com.cn.domain.impl.Chinexe">
<constructor-arg ref="stoneAxe" type="com.cn.domain.Axe"></constructor-arg>
</bean>
<bean id="stoneAxe" class="com.cn.domain.impl.StoneAxe" />
<!-- 配置steelAxe实例,其实现类是SteelAxe -->
<bean id="steelAxe" class="com.cn.domain.impl.SteelAxe" />
</beans>
PS;set注入·只需把<constructor-arg name="axe" ref="steelAxe"></constructor-arg>换成<property name="axe" ref="axe"/>
完成以上内容
简单的依赖注入就算完成了。