Springboot利用xml配置文件方的式注入bean

本文介绍如何在SpringBoot项目中通过XML配置文件注入DefaultManageableImageCaptchaService等bean,解决生成验证码图片时的依赖注入问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

引子:
在生成验证码图片的时候需要用到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了。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值