转载

【java实例】自己动手实现IOC和MVC(六)

下面来对现在ioc做的简单测试 UserDao.Java 模拟数据库的操作
  1. package com.ajun.test.dao;
  2. import com.ajunframework.beans.annotation.Dao;
  3. @Dao
  4. public class UserDao {
  5.     public void add(){
  6.         System.out.println("UserDao's add method was called");
  7.     }
  8. }
UserService.java模拟业务层的操作
  1. package com.ajun.test.service;
  2. import com.ajun.test.dao.UserDao;
  3. import com.ajunframework.beans.annotation.Property;
  4. import com.ajunframework.beans.annotation.Service;
  5. @Service
  6. public class UserService {
  7.     @Property
  8.     private UserDao userDao;//注入属性
  9.     public void add(){
  10.         System.out.println("UserService's add method was called");
  11.         userDao.add();
  12.     }
  13.     public UserDao getUserDao() {
  14.         return userDao;
  15.     }
  16.     public void setUserDao(UserDao userDao) {
  17.         this.userDao = userDao;
  18.     }
  19. }
UserAction.java模拟action层得操作
  1. package com.ajun.test.action;
  2. import com.ajun.test.service.UserService;
  3. import com.ajunframework.beans.annotation.Action;
  4. import com.ajunframework.beans.annotation.Property;
  5. @Action
  6. public class UserAction {
  7.     @Property
  8.     private UserService userService;//注入属性
  9.     public void add(){
  10.         System.out.println("UserAction's add method was called");
  11.         userService.add();
  12.     }
  13.     public UserService getUserService() {
  14.         return userService;
  15.     }
  16.     public void setUserService(UserService userService) {
  17.         this.userService = userService;
  18.     }
  19. }
下面是测试方法
  1. package com.ajun.test;
  2. import com.ajun.test.action.UserAction;
  3. import com.ajunframework.beans.applicationContext.AnnotationClassPathApplicationContext;
  4. import com.ajunframework.beans.applicationContext.ClassPathApplicationContext;
  5. import com.ajunframework.beans.factory.AnnotationBeanFactory;
  6. public class Test {
  7.     public static void main(String [] ag){
  8.         ClassPathApplicationContext cx =
  9.             AnnotationClassPathApplicationContext.getAnnotationClassPathApplicationContext();
  10.         cx.init();
  11.         UserAction action = AnnotationBeanFactory.getBeanFactory().getBean("userAction",UserAction.class);
  12.         action.add();
  13.     }
  14. }
打印结果:
  1. UserAction's add method was called
  2. UserService's add method was called
  3. UserDao's add method was called
ioc这个project只是给大家提供个思路而已,现在ioc只是实现singleton 而没有实现prototype ,如果大家有思路 ,可以讨论一下,肯定是会用到prototype模式的。 下一节我会给大家mvc的实现  
正文到此结束
Loading...