原文:java利用反射机制模拟spring IOC实现
源代码下载地址:http://www.zuidaima.com/share/1724245276724224.htm
第一步:定义服务的配置文件(指定服务名和服务路径)
1 | <?xml version= "1.0" encoding= "gb2312" ?> |
2 | <!-- DOCTYPE service - config SYSTEM " service.dtd " --> |
5 | <service name= "UserService " class = "com.xainfor.service.UserService" template= "normal" /> |
6 | <service name= "GnmkService" class = "com.xainfor.service.GnmkService" template= "normal" /> |
第二步:系统初始化是将所有服务名和路径加载到一个静态的HashMap中
01 | public class ServiceConfig { |
03 | public static HashMap serviceMap= new HashMap(); |
05 | public static String getService(String serviceName) { |
06 | String serviceClass= "" ; |
07 | serviceClass= ServiceConfig.serviceMap.get(serviceName).toString(); |
第三步:定义一个接口类
1 | public interface Service { |
第四步:服务实例化类
01 | public class ServiceExecuteHelper { |
06 | private static final MsgLogger logger=MsgLogger.getLogger(); |
08 | public static void execute(String servicename) { |
11 | String servicClass=ServiceConfig.getService(servicename); |
13 | if (servicClass != null && !servicClass.equals( "" )) { |
14 | Class classObject=Class.forName(servicClass); |
15 | Service service=(Service) classObject.newInstance(); |
18 | logger.info( "服务[" +servicename+ "]未定义" ); |
21 | logger.info( "服务[" +servicename+ "]不存在!" ); |
第五步:定义接具体服务并实现接口类
01 | public class GnmkService implements Service { |
06 | public void execute() { |
08 | System.out.println( "执行的是GnmkService" ); |
1 | public class UserService implements Service { |
3 | public void execute() { |
5 | System.out.println( "执行的是UserService" ); |
第六步:测试类
1 | public class testService { |
3 | public static void main(String[] temp) { |
4 | ServiceExecuteHelper.execute( "UserService" ); |