生成验证码的逻辑原理 (不想看原理可直接看重写)
首先用@bean注解注入了DefaultKaptcha对象,但是你会发现@Resource下面的却是Producer,这是因为DefaultKaptcha实现了producer接口
接下来我们来看一下验证码的生成逻辑(capText就是类似:1+1=?)
首先调用了captchaProducerMath.createText();
接着我们看一下他的具体实现
一步一步来看this.getConfig(),这个是哪来的呢,因为DefaultKaptcha继承了子类Configurable
config的内容是从哪来的呢
DefaultKaptcha注入时new了一个config用于装配
properties.setProperty之类的就类似这样的
color : white
address : 广东
所以上面就装配了config了
接下来this.getConfig().getTextProducerImpl()的getTextProducerImpl()
这个函数的paramName是指
所以paramValue是"com.ruoyi.framework.config.KaptchaTextCreator"
接着TextProducer textProducer = (TextProducer)this.helper.getClassInstance(paramName, paramValue, new DefaultTextCreator(), this);
这里调用了this.helper.getClassInstance,我们去具体函数看看,这里的this.helper是啥呢
所以我们去ConfigHelper
这个函数的大概意思是利用java的反射机制实例化了一个类,并返回这个对象,总的来说就是这个函数实例化了paramValue:"com.ruoyi.framework.config.KaptchaTextCreator"这个类
我们去找一下这个类
然后由于转换成了TextProducer类,所以我们去找一下TextProducer类
找到了TextProducer类
找一下哪个类实现了这个接口,发现DefaultTextCreator实现了
然后我们回到this.getConfig().getTextProducerImpl().getText();
到这里其实就是getTextProducerImpl()实例了"com.ruoyi.framework.config.KaptchaTextCreator"这个类,然后调用了getText()方法,getText()是一个重写方法,是从哪里来的呢,就是在TextProducer接口定义了,然后DefaultTextCreator实现了TextProducer接口,然后KaptchaTextCreator继承了DefaultTextCreator,也就是说 this.getConfig().getTextProducerImpl().getText()就是调用了KaptchaTextCreator的getText()方法,也就是生成一串字符串类似1+2=?
重写
而我们要是说不想生成1+2=?之类的,我们只需要把上图的getText()方法重写即可
本文基本上就是讲述capText是怎么来的
如若写得不好,可提些意见。本文虽然说是研究若依源码,其实是研究
com.google.code.kaptcha
这个包