您的位置:首页 > 其它

003-搭建框架-实现IOC机制

2017-10-12 21:36 176 查看
一、实现目标

一种MVC【Model-View-Controller】一种设计模式,进行解耦。

/*
* 处理客户管理相关请求
*/
@Controller
public class CustomerController {
@Inject
private CustomService customService;

@Action("get:/customer")
public View index(Param param) {
List<Customer> customerList = customService.getCustomerList("");
return new View("customer.jsp").addModel("customerlist", customerList);
}

@Action("get:/customer_show")
public View show(Param param) {
long id = param.getLong("id");
Customer customer = customService.getCustomer(id);
return new View("customer_show.jsp").addModel("customer", customer);
}

@Action("get:/customer_create")
public View create(Param param) {
return new View("customer_create.jsp");
}

@Action("post:/customer_create")
public Data createSumbit(Param param) {
Map<String, Object> paramMap = param.getParamMap();
boolean result = customService.createCustomer(paramMap);
return new Data(result);
}

@Action("get:/customer_edit")
public View edit(Param param) {
long id = param.getLong("id");
Customer customer = customService.getCustomer(id);
return new View("customer_edit.jsp").addModel("customer", customer);
}

@Action("post:/customer_edit")
public Data editSumbit(Param param) {
long id = param.getLong("id");
Map<String, Object> paramMap = param.getParamMap();
boolean result = customService.updateCustomer(id, paramMap);
return new Data(result);
}

@Action("post:/customer_delete")
public Data delete(Param param) {
long id = param.getLong("id");
boolean result = customService.deleteCustomer(id);
return new Data(result);
}
}


注:

  通过@Controller注解来定义Controller类;通过注解@Inject来定义成员属性;

  通过@Service注解来定义Service类,通过注解@Action来定义方法;

  返回View 对象标示jsp页面,Data标示JSon数据

二、代码开发

  https://github.com/bjlhx15/smart-framework.git 中的chapter3和smart-framework部分

三、知识点

3.1、类加载器

package com.lhx.smart.framework.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
* 反射工具类
*/
public final class ReflectionUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(ReflectionUtil.class);

/**
* 创建实例
*
* @param cls
* @return
*/
public static Object newInstance(Class<?> cls) {
Object instance;
try {
instance = cls.newInstance();
} catch (Exception e) {
LOGGER.error("实例化失败", e);
throw new RuntimeException(e);
}
return instance;
}

/**
* 调用方法
*
* @param obj
* @param method
* @param args
* @return
*/
public static Object invokeMethod(Object obj, Method method, Object... args) {
Object result;
try {
method.setAccessible(true);
result = method.invoke(obj, args);
} catch (Exception e) {
LOGGER.error("调用方法失败", e);
throw new RuntimeException(e);
}
return result;
}

public static void setFiled(Object obj, Field field, Object value) {
try {
field.setAccessible(true);
field.set(obj, value);
} catch (Exception e) {
LOGGER.error("参数设置失败", e);
throw new RuntimeException(e);
}
}
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐