上文我们通过注解的方式 实现了 spring 容器的 初始化
下面我们通过 配置xml文件的方式 来同样实现 spring 容器的初始化
//创建一个消息服务类
public class MessageService {
......
}
//创建一个打印机类
public class MessagePrinter {
}
既然要通过 xml 配置 的方式来实现 那我们首先需要创建一个xml
在 Maven 项目的 resources 文件夹下 我们通过
鼠标右键 -> New -> XML Configuration File -> Spring Config 的方式 来创建一个名为
applicationContext.xml 的 spring 配置文件
在 applicationContext.xml 中添加如下标签
<!--
bean元素: 描述当前的对象需要spring 容器管理
id属性:标识对象,未来在应用程序中可以根据id获取对象
class:被管理对象的类全名
-->
<bean id="service" class="hello.MessageService"></bean>
<bean id="printer" class="hello.MessagePrinter"></bean>
这个时候 spring 就会自动创建这些类的实例对象
public class Application {
public static void main(String[] args) {
//基于XML 的方式 初始化 spring容器
//ClassPathXmlApplicationContext() 该类传递 xml 配置文件的filepath
ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml" );
//调用 printer.getBean() 方法获取 bean 对象
MessagePrinter printer = context.getBean( MessagePrinter.class ); //获取printer对象
MessageService service = context.getBean(MessageService.class); //获取service对象
printer.setService(service); //传递service对象
printer.printMessage();
}
}