使用设计模式创建多渠道
package com.job.center.quartz.service; /** * @author 周志伟 * @projectname 项目名称: ${project_name} * @classname: PayService * @description: 支付接口 * @date 2018/10/12:9:10 */ public interface PayService { public String sum(String key); }
package com.job.center.quartz.service.pay; import com.job.center.quartz.common.Pay; import com.job.center.quartz.dao.QrtzLogMapper; import com.job.center.quartz.service.PayService; import com.job.center.quartz.vo.QrtzLogDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @author 周志伟 * @projectname 项目名称: ${project_name} * @classname: PayServiceImpl * @description: * @date 2018/10/12:9:11 */ @Pay(falg = 11) @Service("com.job.center.quartz.service.pay.PayServiceImpl") public class PayServiceImpl implements PayService { @Autowired private QrtzLogMapper dao; @Override public String sum(String key) { QrtzLogDTO qrtzLogDTO= dao.findQrtzLogByPrimaryKey(key); return "363666"; } }
package com.job.center.quartz.common; import com.job.center.quartz.service.PayService; import org.reflections.Reflections; import java.util.HashMap; import java.util.Set; /** * @author 周志伟 * @projectname 项目名称: ${project_name} * @classname: Payfactory * @description: * @date 2018/10/12:9:12 */ public class Payfactory { private Payfactory(){} /** * 饿汉式单利(线程安全) */ private static Payfactory single = new Payfactory(); public static Payfactory getInstance() { return single; } private static HashMap<Integer,String> map=new HashMap<Integer,String>(); public static PayService create(int id) throws Exception { return (PayService) SpringUtil.getBean(map.get(id)); } static { Reflections reflections = new Reflections("com.job.center.quartz.service.pay"); Set<Class<?>> set= reflections.getTypesAnnotatedWith(Pay.class); for (Class<?> el : set){ Pay annotation = el.getAnnotation(Pay.class); int key =annotation.falg(); String value=el.getName(); map.put(key,value); } } }
package com.job.center.quartz.controller; import com.job.center.quartz.common.Payfactory; import com.job.center.quartz.service.PayService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author 周志伟 * @projectname 项目名称: ${project_name} * @classname: TestController * @description: * @date 2018/10/12:15:10 */ @RestController @RequestMapping public class TestController { @Autowired private PayService payService; @RequestMapping("/TEST") public void test() throws Exception { Payfactory payfactory =Payfactory.getInstance(); payService=payfactory.create(11); payService.sum("11111"); } }
//反射类需要用到的包
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>RELEASE</version>
</dependency>