引子:
在生成验证码图片的时候需要用到com.octo.captcha.service.image.DefaultManageableImageCaptchaService,但是springboot没有提供给applicationcontext.xml文件,无法利用xml配置文件方式注入。
如图所示直接采用注解的方式,启动会报错
解决方法
利用xml配置文件的方式注入bean
步骤如下
1、创建一个xml配置文件captcha.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<!-- 验证码 -->
<bean id="imageCaptchaService" class="com.octo.captcha.service.image.DefaultManageableImageCaptchaService">
<constructor-arg type="com.octo.captcha.service.captchastore.CaptchaStore" index="0">
<ref bean="fastHashMapCaptchaStore"/>
</constructor-arg>
<!-- which captcha Engine you use -->
<constructor-arg type="com.octo.captcha.engine.CaptchaEngine" index="1">
<ref bean="captchaEngineGenerator"/>
</constructor-arg>
<constructor-arg index="2">
<value>180</value>
</constructor-arg>
<constructor-arg index="3">
<value>100000</value>
</constructor-arg>
<constructor-arg index="4">
<value>75000</value>
</constructor-arg>
</bean>
<bean id="fastHashMapCaptchaStore" class="com.octo.captcha.service.captchastore.FastHashMapCaptchaStore"/>
<!-- you can define more than one captcha engine here -->
<!-- <bean id="captchaEngineGenerator" class="com.xxx.ott.mcms.utils.CaptchaEngineGenerator"/> -->
</beans>
配置文件路径为:/src/main/resources/captcha.xml
2、在启动类上加上@ImportResource(locations = {“classpath:captcha.xml”})注解:
@ImportResource:引入spring配置文件.xml
3、在Controller下引入:
通过以上三个步骤就可以实现利用xml配置文件方的式注入bean了。