java利用反射机制模拟spring IOC实现

原文:java利用反射机制模拟spring IOC实现

源代码下载地址:http://www.zuidaima.com/share/1724245276724224.htm

第一步:定义服务的配置文件(指定服务名和服务路径)

1 "1.0" encoding="gb2312" ?>
2  
3  
4  
5  "UserService " class="com.xainfor.service.UserService" template="normal" />
6  "GnmkService" class="com.xainfor.service.GnmkService" template= "normal" />
7  

第二步:系统初始化是将所有服务名和路径加载到一个静态的HashMap中

01 public class ServiceConfig {
02   
03     public static HashMap serviceMap= new HashMap();
04   
05     public static String getService(String serviceName) {
06     String serviceClass= "";
07     serviceClass= ServiceConfig.serviceMap.get(serviceName).toString();
08        return serviceClass;
09     
10  }


第三步:定义一个接口类

1 public interface Service {
2  public void execute();
3 }

第四步:服务实例化类

01 public class ServiceExecuteHelper {
02   
03  /** *//**
04  * 日志处理
05  */
06  private static final MsgLogger logger=MsgLogger.getLogger();
07   
08  public static void execute(String servicename) {
09          try {
10              //验证服务是否存在
11             String servicClass=ServiceConfig.getService(servicename);
12             //如果服务存在就加载服务信息
13             if (servicClass !=null && !servicClass.equals("")) {
14                  Class classObject=Class.forName(servicClass);
15                  Service service=(Service) classObject.newInstance();
16                  service.execute();
17              else {
18                  logger.info("服务["+servicename+"]未定义");
19              }
20            }catch(Exception e) {
21                logger.info("服务["+servicename+"]不存在!");
22            }
23         }
24 }

第五步:定义接具体服务并实现接口类

01 public class GnmkService implements Service {
02  
03           /**//* (non-Javadoc)
04            * @see com.xainfor.service.Service#println()
05            */
06           public void execute() {
07             // TODO Auto-generated method stub
08            System.out.println("执行的是GnmkService");
09           }
10  
11 }
1 public class UserService implements Service {
2   
3                   public void execute() {
4                      // TODO Auto-generated method stub
5                      System.out.println("执行的是UserService");
6                   }
7 }

第六步:测试类

1 public class testService {
2   
3            public static void main(String[] temp) {
4                ServiceExecuteHelper.execute("UserService");
5            }
6 }

 



你可能感兴趣的:(java)