• spring 03-Spring开发框架之控制反转


    控制反转原理

    测试接口程序

    package cn.liang.service;
    public interface IMessageService {
    	public String getInfo() ;
    }
    
    package cn.liang.service.impl;
    import cn.liang.service.IMessageService;
    public class MessageServiceImpl implements IMessageService {
    	@Override
    	public String getInfo() {
    		return "helloliang";
    	}
    }
    

    原始对象调用

    • 在java开发中需要通过使用关键字new来进行对象产生,耦合度加深。
    • new是造成代码耦合度关键的元凶
    package cn.liang.test;
    import cn.liang.service.IMessageService;
    import cn.liang.service.impl.MessageServiceImpl;
    public class TestMessage2 {
    	public static void main(String[] args) {
    		IMessageService msg = new MessageServiceImpl();
    		System.out.println(msg.getInfo());
    	}
    }
    
    • 可以通过引入一个专门负责具体操作的代理公司开发,这样可以避免关键字new
    package cn.liang.service;
    import static org.hamcrest.CoreMatchers.nullValue;
    public class ServiceFactory {
    	public static IMessageService getInstance(String className) {
    		IMessageService msg = null;
    		try {
    			msg = (IMessageService) Class.forName(className).newInstance();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return msg;
    	}
    }
    
    package cn.liang.test;
    import cn.liang.service.IMessageService;
    import cn.liang.service.ServiceFactory;
    public class TestMessage3 {
    	public static void main(String[] args) {
    		IMessageService msg = ServiceFactory.getInstance("cn.liang.service.impl.MessageServiceImpl");
    		System.out.println(msg.getInfo());
    	}
    }
    

    使用Spring开发框架进行代理

    修改applicationContext.xml配置文件:

    <bean id="msg" class="cn.liang.service.impl.MessageServiceImpl"/>
    

    编写测试程序代码类

    • 现阶段是通过java程序启动了Spring容器,后面可以利用WEB容器来启动Spring容器
    • 最后整个阶段不会看见任何的关键字new的出现
    package cn.liang.test;
    import org.apache.log4j.Logger;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import cn.liang.service.IMessageService;
    import junit.framework.TestCase;
    public class TestMessageService {
    	private static ApplicationContext ctx = null ;
    	static {	// 静态代码块优先于所有的代码执行,目的是为了静态属性初始化
    		ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
    	}
    	@Test
    	public void testGetInfo() {
    		IMessageService msgService = ctx.getBean("msg", IMessageService.class);
    		Logger.getLogger(TestMessageService.class).info(msgService.getInfo());
    		TestCase.assertEquals(msgService.getInfo(), "helloliang");
    	}
    }
    
  • 相关阅读:
    hibernate 总结
    事物随笔
    添加收藏夹的作法
    jquery uploadify多文件上传
    过滤器与拦截器的区别
    网站首页添加缓存--------ehcache的简单使用
    DWR 在项目中的应用
    分页标签:pager-taglib的使用
    关闭iptables(Centos)
    Centos移除图形界面
  • 原文地址:https://www.cnblogs.com/liangjingfu/p/10037323.html
Copyright © 2020-2023  润新知