您的位置:首页 > 编程语言 > Java开发

【Spring】——IOC配置对象实例

2017-02-11 21:00 330 查看
        上一篇我们简单介绍了Spring的原理以及IOC,这次小编带大家了解Spring是如何实现管理创建、依赖对象的。我们通过一个实例进行了解。

       
首先看实例的目录结构:



        其中实现管理对象的是applicationContext.xml。它是spring的核心配置文件。

        当不使用spring时,我们想要实现添加用户

        Client——>UserManager——>UserDao,会有两层依赖关系。

        如:

       Client中:

       UserManager userManager=new UserManager();

       userManager.addUser(username,password);

       UserManager中:

       UserDao userDao=new UserDao4MySqlImpl();

       userDao.addUser(username,password);

       即Client依赖UserManager,UserManager 依赖UserDao

        当然我们也可以使用工厂,来决定使用MySql还是Oracle。但使用工厂是一个工厂对应一个产品,在这里即对应一个Dao层实现。
       所以在此我们更倾向用spring的容器对
对象进行管理:

       首先,将类进行基本配置,这也就相当于一个工厂:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"> 
<bean id="userDao4Mysql" class="com.bjpowernode.spring.dao.UserDao4MySqlImpl"/>

<bean id="usrDao4Oracle" class="com.bjpowernode.spring.dao.UserDao4OracleImpl"/>

<bean id="userManager" class="com.bjpowernode.spring.manager.UserManagerImpl">

</bean>
</beans>


        那userManager中用的Dao。怎么拿,这需要我们继续配置:

<?xml version="1.0" encoding="UTF-8"?>

<bean id="userManager" class="com.bjpowernode.spring.manager.UserManagerImpl">

<constructor-arg ref="userDao4Mysql"/> 这就相当于userManager的构造函数

<!--
<constructor-arg ref="usrDao4Oracle"/> 二者选一
-->
</bean>
        这样,当我们调userManager时,它会根据配置自动找到userDao。并自动实例对象将其返回。

         至此,我们就配置好了,现在就可以访问了

       Client中:

       首先读取配置文件

BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
       然后获得对象:

UserManager userManager = (UserManager)factory.getBean("userManager");
       至此,直接就可使用userDao的方法

userManager.addUser("张三", "123");


        所以,简单的几句,我们就从客户端访问到了Dao层,并且整个功能实现过程中,我们并没有看到Dao层的实现,也没有实例Dao层,但能访问到Dao的方法,这就是spring的IOC的功劳,一方面,它为我们减少了工厂的使用,同时减少了代码中的耦合,使得我们的代码层次更清晰。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: