`
DavyJones2010
  • 浏览: 155024 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Spring 3.0: A Mocking Example for Explaining Basic Spring IoC Mechanism

阅读更多

1. Beans

package beans;

public class User
{
	private String username;
	private String password;
	
	public User()
	{
	}
	public User(String username, String password)
	{
		this.username = username;
		this.password = password;
	}
	public String getUsername()
	{
		return username;
	}
	public void setUsername(String username)
	{
		this.username = username;
	}
	public String getPassword()
	{
		return password;
	}
	public void setPassword(String password)
	{
		this.password = password;
	}
}

 2. Dao

package dao;

import beans.User;

public interface UserDao
{
	public void addUser(User user);
	public void delUser(User user);
	public void modUser(User user);
	public User getUser(String username);
}

 3. Dao Impl

package dao.impl;

import beans.User;
import dao.UserDao;

public class UserDaoMySQLImpl implements UserDao
{
	@Override
	public void addUser(User user)
	{
		// TODO Auto-generated method stub
		System.out.println("User added to MySQL");
	}

	@Override
	public void delUser(User user)
	{
		// TODO Auto-generated method stub
		System.out.println("User deleted in MySQL");
	}

	@Override
	public void modUser(User user)
	{
		// TODO Auto-generated method stub
		System.out.println("User modified in MySQL");
	}

	@Override
	public User getUser(String username)
	{
		// TODO Auto-generated method stub
		System.out.println("User gotten from MySQL");
		return new User();
	}
}

 4. Service

package service;

import beans.User;
import dao.UserDao;

public class UserService
{
	private UserDao userDao;
	
	public UserService()
	{
	}
	
	public UserDao getUserDao()
	{
		return userDao;
	}
	public void setUserDao(UserDao userDao)
	{
		this.userDao = userDao;
	}
	public void addUser(User user)
	{
		//UserDao only has the responsibility of communicating with DB
		//UserService have more logical responsibility
		//Authentication or Right check
		userDao.addUser(user);
	}
	public void delUser(User user)
	{
		userDao.delUser(user);
	}
	public void modUser(User user)
	{
		userDao.modUser(user);
	}
	public User getUser(String username)
	{
		return userDao.getUser(username);
	}
}

 5. beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans>
	<bean id="userService" class="service.UserService">
		<property id="userDao" class="dao.impl.UserDaoOracleImpl"/>
	</bean>
</beans>

 6. Test

package jdom;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.junit.Test;

import service.UserService;
import beans.User;
import dao.UserDao;

public class JDomTest
{
	@Test
	public void parse() throws Exception
	{
		String xmlPath = "bin/beans.xml";
		SAXBuilder saxBuilder = new SAXBuilder();

		try
		{
			Document document = saxBuilder.build(xmlPath);

			Element beans = document.getRootElement();

			List<Element> beanList = beans.getChildren();

			for (Iterator<Element> iter = beanList.iterator(); iter.hasNext();)
			{
				Element bean = iter.next();

				String beanName = bean.getAttributeValue("id");
				String beanClassName = bean.getAttributeValue("class");

				System.out.println("BeanName: " + beanName);
				System.out.println("BeanClass: " + beanClassName);

				// Generate bean instance
				Class<?> beanClass = Class.forName(beanClassName);
				UserService beanInstance = (UserService) beanClass
						.newInstance();

				Element beanProp = bean.getChild("property");

				String beanPropName = beanProp.getAttributeValue("id");
				String beanPropClass = beanProp.getAttributeValue("class");
				System.out.println("PropertyName: " + beanPropName);
				System.out.println("PropertyClass: " + beanPropClass);
				// Generate property instance
				Class<?> propertyClass = Class.forName(beanPropClass);
				UserDao propertyInstance = (UserDao) propertyClass
						.newInstance();

				// Invoke setUserDao function in beanInstance
				beanInstance.setUserDao(propertyInstance);

				beanInstance.addUser(new User());
				beanInstance.delUser(new User());
				beanInstance.modUser(new User());
				beanInstance.getUser("Davy");
			}
		} catch (JDOMException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 

Comments:

        1. Using XML file as configuration file for Dependency Injection (Inverse of Control).

        2. Using JDom-2.0.4 for resolving XML file.

        3. Using Reflection for instantiating beans & properties dynamicly according to the value got from XML, then assembly them dynamicly.

        4. Using JUnit4 for testing.

        5. Special thanks to Shibing,Ma for his fantastic tutorials which inspired me so generously.

 

Modified:

1. Remove JDomTest.java, add Factory to be much more like that in real Spring

package factory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import service.UserService;
import dao.UserDao;

public class ClassPathXmlApplicationContext
{
	private Map<String, Object> beansMap = new HashMap<String, Object>();

	public ClassPathXmlApplicationContext()
	{
		String xmlPath = "bin/beans.xml";
		SAXBuilder saxBuilder = new SAXBuilder();

		Document document;
		try
		{
			document = saxBuilder.build(xmlPath);
			Element beans = document.getRootElement();

			List<Element> beanList = beans.getChildren();

			for (Iterator<Element> iter = beanList.iterator(); iter.hasNext();)
			{
				Element bean = iter.next();

				String beanName = bean.getAttributeValue("id");
				String beanClassName = bean.getAttributeValue("class");

				System.out.println("BeanName: " + beanName);
				System.out.println("BeanClass: " + beanClassName);

				// Generate bean instance
				Class<?> beanClass = Class.forName(beanClassName);
				UserService beanInstance = (UserService) beanClass.newInstance();

				Element beanProp = bean.getChild("property");

				String beanPropName = beanProp.getAttributeValue("id");
				String beanPropClass = beanProp.getAttributeValue("class");
				System.out.println("PropertyName: " + beanPropName);
				System.out.println("PropertyClass: " + beanPropClass);
				// Generate property instance
				Class<?> propertyClass = Class.forName(beanPropClass);
				UserDao propertyInstance = (UserDao) propertyClass.newInstance();

				// Invoke setUserDao function in beanInstance
				beanInstance.setUserDao(propertyInstance);

				beansMap.put(beanName, beanInstance);
			}
		} catch (JDOMException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public Object getBean(String name)
	{
		return beansMap.get(name);
	}
}

 2. Substract test case to a new source folder called test in the same level with src folder. The class to be tested should be in the same package with the test case class. But in different source folder.

package service;

import org.junit.Test;

import beans.User;
import factory.ClassPathXmlApplicationContext;

public class UserServiceTest
{
	private ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();
	private UserService userService = (UserService)context.getBean("userService");
	
	@Test
	public void testAddUser()
	{
		userService.addUser(new User());
	}
}

 

分享到:
评论

相关推荐

    spring 3.0 jar包

    Spring 3.0是Spring框架的一个重要版本,它在2009年发布,为Java开发者带来了许多新特性和改进。这个版本标志着Spring框架在企业级应用开发中的成熟,提供了更强大、更灵活的解决方案。 1. **依赖注入增强**: ...

    Learning EasyMock3.0 By Official Example

    总结来说,《Learning EasyMock3.0 By Official Example》是一个深入了解和掌握 EasyMock 的宝贵资源。通过学习官方示例,开发者不仅能学会如何创建和管理模拟对象,还能了解如何在实际项目中有效地应用这些技术,...

    spring教程

    本教程旨在深入探讨Spring的核心概念和技术,通过提供的两份教程文档——"Learning Spring Application Development.pdf"和"Mockito for Spring.pdf",我们可以深入了解Spring的精髓。 "Learning Spring ...

    mimid:HTTP Mocking库

    咪咪HTTP Mocking库Mimid尝试简化HTTP API模拟的创建。这个怎么运作代理人最初,mimid充当您的服务和外部API之间的代理,捕获所有HTTP请求和响应。 mimid proxy http://api.3rd-pary.com 注意:您需要将服务配置为...

    asMock: ActionScript Mocking Framework-开源

    asMock是用于Flex / Flash(AS3)的动态模拟框架。 可以在asMock网站上找到包括新闻,教程和API文档在内的更多信息:http://asmock.sourceforge.net/

    Mockito for Spring(PACKT,2015)

    This book will provide you with the skills you need to successfully build and maintain meaningful unit and integration test cases for Spring Framework code. This book starts with a brief introduction...

    JAVA spring 的介绍.docx

    3. **易于测试**:Spring 设计时考虑到了便于编写单元测试的需求,支持对底层依赖的模拟(Mocking)。 4. **全面性**:Spring 提供了包括但不限于 IoC、AOP、Web MVC、ORM 支持、数据库访问等功能,覆盖了大部分企业...

    spring-cglib-repack-3.2.5.jar spring-objenesis-repack-2.6.jar spring依赖包

    Objenesis能够非常快速地创建对象,即使是在类没有无参构造函数或者构造函数有特定权限限制的情况下,这对于Spring的测试和Mocking机制非常重要。 `repack`这个词缀可能表示这些jar文件是经过重新打包的版本,可能...

    spring-boot-reference.pdf

    10.2.6. Quick-start Spring CLI Example 10.3. Upgrading from an Earlier Version of Spring Boot 11. Developing Your First Spring Boot Application 11.1. Creating the POM 11.2. Adding Classpath ...

    Spring.net-2.0.1GA版项目文件

    7. **单元测试和Mocking**:Spring.NET提供了测试支持,包括IoC容器的测试上下文,以及用于模拟对象的设施,便于编写单元测试。 8. **配置管理**:Spring.NET的XML配置文件可以灵活地定义对象、依赖关系和行为,...

    spring-framework-4.2.2.RELEASE

    Spring Framework 4.2.2.RELEASE 是Spring Framework 家族中的一个版本,它在2015年左右发布。Spring Framework是Java平台上一个开源的、全面的、模块化的、轻量级的和企业级的Java应用开发框架,尤其适用于Java EE...

    spring-boot-test示例程序

    在IT行业中,Spring Boot是一个非常流行的Java框架,用于简化微服务和Web应用的开发。它提供了许多开箱即用的功能,使得开发者可以快速构建可运行的应用。本示例程序是关于"Spring Boot Test"的实践,它展示了如何...

    Spring中进行集成测试

    1. **Spring Test Framework**:Spring Test模块为Spring应用程序提供了一个统一的测试平台,它包括了`@RunWith(SpringRunner.class)`注解,允许JUnit测试类利用Spring的IoC容器进行初始化。通过这个注解,你可以将...

    spring入门笔记

    **Spring 框架概述** Spring 是一个开源的 Java 应用框架,它以其轻量级、模块化和面向切面编程(AOP)的特性而著名。Spring 的设计目标是简化Java企业级应用开发,它提供了一种有效的方式来管理对象的生命周期和...

    spring编辑器

    标题 "spring编辑器" 暗示我们讨论的是与Spring框架相关的开发工具,可能是用于编辑、配置或调试Spring应用的工具。描述中的链接指向了一篇2019年的博客文章,但无法直接访问以获取详细信息。不过,我们可以基于...

    spring完整jar包(Spring Framework version 3.2.0.M1)

    13. **Improved Testing Support**:Spring 3.2 增强了测试支持,包括模拟(Mocking)和代理(Stubbing)的改进,以及对Web应用程序的测试工具。 14. **Performance Enhancements**:Spring 3.2 进行了一系列性能...

    spring.net 中文文档

    6. **单元测试和模拟对象(Mocking)**:Spring.NET提供了一套测试支持,包括模拟对象框架,方便进行单元测试和集成测试,确保代码质量。 7. **企业服务支持**:Spring.NET集成了对JMS、WS-*/SOAP Web服务、EJB以及...

    spring-test.zip

    Spring框架是Java开发中的一个核心组件,主要用于简化企业级应用的开发。`spring-test.zip`文件包含的是关于Spring测试的相关代码示例,这对于理解和掌握Spring框架的测试支持至关重要。Spring Test模块提供了集成...

Global site tag (gtag.js) - Google Analytics