Spring(二):Spring Ioc简介

上一章节:Spring原理(一):模拟Spring Ioc


上一章节我们模拟了Spring Ioc,这章节使用Spring来实现同样的功能,其余部分不变,主要变动的是beans.xml和UserServiceTest类里面的内容。

注意:需要导入Spring和commons-logging的jar包


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="userDAO" class="com.castiel.dao.impl.UserDAOImpl"/>
    <!-- bean标签中的id="userDAO"可以换成name="userDAO",区别就是name可以用特殊字符(比如可以使用类的全名'com.xxx.xxx.xxx'来作为值) -->
    <!-- id取值要求严格些,必须满足XML的命名规范。id是唯一的,配置文件中不允许出现两个id相同的<bean> -->
    <!-- name名称可以重复,在配置文件中允许出现两个name相同的<bean>,在用getBean()返回实例时,后面一个Bean被返回 -->
   <!-- 如果没有id,name,则用类的全名作为name,如<bean class="test.Test">,可以使用getBean("test.Test")返回该实例 -->
    <bean id="userService" class="com.castiel.service.UserService">
        <property name="userDAO" ref="userDAO" />
        <!-- 或另一种写法 -->
        <!-- <property name="userDAO">
        	<ref bean="userDAO"/>
        </property> -->
    </bean>
</beans>


UserServiceTest内容如下:

package com.castiel.service;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.castiel.model.User;
import com.castiel.service.UserService;

public class UserServiceTest {
	/**测试类生成方式**/
	/**
	 * 1.选中src下com.castiel.service包中的UserService
	 * 2.右键new jUnit Test Case
	 * 3.点击NEXT
	 * 4.选择需要测试的方法
	 * 5.点击Finish
	 * 6.把生成出来的*Test.java文件拖到test下com.castiel.service包中
	 * @throws Exception 
	 */
	@Test
	public void testAdd() throws Exception {
		/*
		 * 方法1,传统方式,使用此种方式,在UserService的add方法中,
		 * userDAO为空,程序报错
		*/
		/*UserService service = new UserService();
		User u = new User();
		service.add(u);*/
		//方法1结束!
		/**
		 * 自动装配,将userDAO注入到userService,注入方式:setter注入和构造器注入
		 */
		//使用BeanFactory
		//BeanFactory factory = new ClassPathXmlApplicationContext("beans.xml");
		//UserService userService = (UserService)factory.getBean("userService");
		//建议:使用ApplicationContext,它实现了BeanFactory,实现类功能更强大,可以完成bean生命周期管理。
		//注意:原有方式控制的是实现,因为要new UserDAOImpl,现在控制的是抽象,我们只需要接口,针对接口编程,也称为控制反转。
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
		UserService userService = (UserService)applicationContext.getBean("userService");
		User user = new User();
		userService.add(user);
	}

}

最后实现的结果也是一样的,附图:



项目结构图:




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值