上文说到什么是Spring以及什么是IoC,这篇文章讲解如何使用IoC进行Bean的装配。
装配,即创建对象间的协作关系,也就是DI(依赖注入)。
在Spring中,我们通过IoC容器和配置文件来完成依赖注入。
Spring框架为我们提供了一个IoC容器ApplicationContext(应用上下文)来管理Bean,ApplicationContext的构造方法参数为一个xml配置文件,接下来就以一个HelloWorld来进行说明。
package com.example.assembly;
//创建一个Bean
public class assemblytest {
private String name;
//编写Set方法用于传值注入
public assemblytest(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public void say() {
System.out.println(name+" say:"+"Hello World"+this.hashCode());
}
}
package com.example.assembly;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class assemblyApplication {
public static void main(String[] args) {
// TODO Auto-generated method stub
//创建ApplicationContext
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("HelloConfig.xml");
//通过ApplicationContext来获得Bean
assemblytest test1 = (assemblytest)context.getBean("hello");
assemblytest test2 = (assemblytest)context.getBean("hello");
test1.say();
test2.say();
context.close();
}
看上面这段代码,与不使用Ioc容器最大的不同就是我们取得对象不再通过New,而是通过ApplicationContext的getBean方法。为何我们能这样做,原因就是创建ApplicationContext对象时的参数——.xml的配置文件。
这个配置文件是这样写的:
<?xml version="1.0" encoding="UTF-8"?>
<!--Spring 配置文件的模板-->
<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.xsd" >
<!--配置assemblytest这个Bean -->
<bean id="hello" class="com.example.assembly.assemblytest">
<property name="name" value="yuanran"/>
</bean>
</beans>
通过配置文件我们实际上是告诉SpringIoC容器,将assemblytest这个类创建一个Bean(这里涉及Bean的作用域,以后讲解),它的Bean ID为"hello",所以我们能通过"hello"来获取这个类的实例。里面的property标签就对应assemblytest类的属性,value即初始化的值。到这里,一次简单的Bean装配就完成了。