第一步:定义服务的配置文件(指定服务名和服务路径)
<?xml version="1.0" encoding="gb2312" ?> <!-- DOCTYPE service - config SYSTEM " service.dtd " --> <service - config> <!-- 用户服务 --> <service name="UserService " class="com.zuidaima.service.UserService" template="normal" /> <service name="GnmkService" class="com.zuidaima.service.GnmkService" template= "normal" /> </service - config>
原创不易,转载请注明出处:java利用反射机制模拟spring IOC实现
代码下载地址:http://www.zuidaima.com/share/1724245276724224.htm
第二步:系统初始化是将所有服务名和路径加载到一个静态的HashMap中
package com.zuidaima; public class ServiceConfig { public static HashMap serviceMap= new HashMap(); public static String getService(String serviceName) { String serviceClass= ""; serviceClass= ServiceConfig.serviceMap.get(serviceName).toString(); return serviceClass; } }第三步:定义一个接口类
public interface Service { public void execute(); }
第四步:服务实例化类
package com.zuidaima; public class ServiceExecuteHelper { /** *//** * 日志处理 */ private static final MsgLogger logger=MsgLogger.getLogger(); public static void execute(String servicename) { try { //验证服务是否存在 String servicClass=ServiceConfig.getService(servicename); //如果服务存在就加载服务信息 if (servicClass !=null && !servicClass.equals("")) { Class classObject=Class.forName(servicClass); Service service=(Service) classObject.newInstance(); service.execute(); } else { logger.info("服务["+servicename+"]未定义"); } }catch(Exception e) { logger.info("服务["+servicename+"]不存在!"); } } }
第五步:定义接具体服务并实现接口类
package com.zuidaima; public class GnmkService implements Service { /**//* (non-Javadoc) * @see com.xainfor.service.Service#println() */ public void execute() { // TODO Auto-generated method stub System.out.println("执行的是GnmkService"); } }