java设计模式-用接口和自定义注解实现
代码结构

第一步:创建接口
package com.chilly.handler.service;
/**
* 业务处理公共的业务接口和业务分类
*/
public interface HandlerService {
public abstract void handler(Object params);
}
第二步:创建实现类
业务处理类1
package com.chilly.handler.service.impl;
import com.chilly.annotation.DBtype;
import com.chilly.handler.service.HandlerService;
import org.springframework.stereotype.Service;
@DBtype(code = "update")
@Service
public class UpdateHandlerServiceImpl implements HandlerService {
@Override
public void handler(Object params) {
System.out.println("update处理业务");
}
}
业务处理类2
package com.chilly.handler.service.impl;
import com.chilly.annotation.DBtype;
import com.chilly.handler.service.HandlerService;
import org.springframework.stereotype.Service;
@DBtype(code = "delete")
@Service
public class DeleteHandlerServiceImpl implements HandlerService {
@Override
public void handler(Object params) {
System.out.println("delete处理业务");
}
}
第三步:工具类
package com.chilly.utils;
import com.chilly.annotation.DBtype;
import com.chilly.handler.service.HandlerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
@Component
public class IHandlerUtils {
@Autowired
private ApplicationContext applicationContext;
public static final Map<String, HandlerService> handlerMap = new HashMap<>();
@PostConstruct
private void initHandler(){
Map<String, HandlerService> handlerServiceMap = applicationContext.getBeansOfType(HandlerService.class);
if(handlerServiceMap != null && handlerServiceMap.size() > 0){
for(HandlerService handlerService : handlerServiceMap.values()){
inintAnnotation(handlerService);
}
}
}
private void inintAnnotation(HandlerService handlerService){
DBtype dBtype = handlerService.getClass().getAnnotation(DBtype.class);
if(dBtype != null && !StringUtils.isEmpty(dBtype.code())){
handlerMap.put(dBtype.code(),handlerService);
}
}
public static HandlerService getHandlerService(String code){
return handlerMap.get(code);
}
}
第四步:controller控制器
package com.chilly.controller;
import com.chilly.handler.service.HandlerService;
import com.chilly.utils.IHandlerUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
public class HandlerController {
@PostMapping("/handler")
public String test(String code, HttpServletRequest request) {
HandlerService handler = IHandlerUtils.getHandlerService(code);
handler.handler(request);
return "handler ok";
}
}
第五步:postMan调用

http://localhost:8989/handler?code=delete
知识点:
1、获取ApplicationContext
https://blog.csdn.net/weixin_38361347/article/details/89304414
2、自定义注解
3、@PostConstruct

浙公网安备 33010602011771号