在开发接口工作中,当你接到需求,发现这个需求是曾相识,检索一下之前的工作记录,猛然发现,这个需求相比之前敲过的需求只是传递的个别参数发生了变化,你会怎么做?在开发一次?不存在的!在这里,我为大家提供一种参考思路,大致如下:
一.编写一个服务接口类,该接口注明要实现的方法,让spring容器管理所有实现该接口的服务类.



在这里,我们先构建一个IGetDoServiceImpl接口,里面声明一个getDoCommand方法.创建SwimmingServiceImpl和RunningServiceImpl并实现IGetDoServiceImpl接口.getDoCommand方法中分别输出不同的两句话.利用spring的@service注解将这两个实现类管理起来.
二.自定义一个注解,让其使用在第一步的每一个服务类上.

接下来我们创建一个注解@SupportCodes,其中@Target表示注解的作用范围@Retention表示注解的生效阶段.里面有一个取值的方法.
三.编写util类,该类获取指定的服务类,来执行服务.



我们定义一个工厂Util.它实现ApplicationContextAware,以便于获得ApplicationContext的实现类,注意,这里一定要添加@Component注解,才能获得ApplicationContext.第二部分是主要内容,里面有一个getServiceImpl的方法,你可以传入接口的类型和注解的内容,就可以得到自己想要的内容,并执行它.

在控制层调用该方法,就能看到控制台输出"you can swimming!"实际生产中,可以当做参数传入以便更好的处理业务,这样写好的一个接口就可以重复利用了.
网友评论