前言
大多数面向对象编程语言,在调用一个类的时候,先要实例化这个类,生成一个对象。
如果现有一个类,过程中要调用到很多其它类,甚至这里的其它类,也要“依赖”于更多其它的类,那么可以想象需要进行多少次实例化,这就是“依赖”的意思。这些对象彼此之间高度耦合,难以复用和测试。
在Spring中,对象无需自己查找或创建与其所关联的其他对象,相反,容器负责把需要相互协作的对象引用赋予各个对象,即依赖注入(DI,Dependency Injection)。
依赖注入: 某个类(不管有多少依赖关系)放入容器(LOC,控制反转)中,可以“解析”出这个类的实例。
-
三种装配方法
- 在XML中进行显示装配
- 在java中进行显示装配
- 隐式bean发现机制和自动装配
在XML中显式装配
user.java
package com.wyx.user;
public class User {
private String name;
private Integer age;
private String sex;
public User(String name,Integer age,String sex){
this.name=name;
this.age=age;
this.sex=sex;
}
//输出JavaBean的属性值方法
public void printInfo(){
System.out.println("用户姓名——"+name);
System.out.println("用户年龄——"+age);
System.out.println("用户性别——"+sex);
}
}
Manger.java
package com.wyx.main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.wyx.user.User;
public class Manger {
public static void main(String[] args) {
ApplicationContext factory = new ClassPathXmlApplicationContext("applicationContext.xml"); // 装载配置文件
User user = (User) factory.getBean("user"); // 获取Bean
user.printInfo();// 输出JavaBean的属性值
}
}
XML配置文件
<?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">
<!-- User Bean -->
<bean name="user" class="com.wyx.user.User">
<constructor-arg>
<value>小强</value>
</constructor-arg>
<constructor-arg>
<value>26</value>
</constructor-arg>
<constructor-arg>
<value>男</value>
</constructor-arg>
</bean>
</beans>