控制反转原理
测试接口程序
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");
}
}