Spring控制反转IOC

来源:互联网 发布:网页分类算法 编辑:程序博客网 时间:2024/05/21 16:54

spring的控制反转(IOC)思想,对象实例不再是由调用者来创建,改为spring容器来创建。spring容器会负责控制程序之间的关系,不再由程序代码直接控制,控制权由应用的代码转向了外部容器,所谓控制反转。spring有两个ioc容器,这里我用的是ApplicationContext。


以一个类为例:

public class UserService {public void addUser(){System.out.println("user add");}}

在xml中注册类,文件名beans.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.xsd"><!-- 生产任意内容 --><bean id="userServiceID" class="com.canyugan.hello.UserService"></bean></beans>

最后我们来段小测试:

<span style="white-space:pre"></span>@Testpublic  void demo1(){ //加载配置文件ApplicationContext applicationContext=new ClassPathXmlApplicationContext("com/canyugan/hello/beans.xml");//从spring的工厂中获取对象UserService userService=(UserService) applicationContext.getBean("userServiceID");userService.addUser();}


最后,欣赏一下spring的ioc强大功能。

1 1
原创粉丝点击