Spring boot 使用xml引入添加其他module对象

本文介绍了如何在Spring Boot项目中通过XML配置引入其他模块的对象,详细讲解了创建XML配置文件、将其添加到Spring容器以及使用@Configuration注解配置类的方法,帮助开发者实现类似SSM框架中的bean管理。

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

最近一个项目 Spring boot 项目需要引入其他 module 中的对象,找了很久希望可以像 SSM 框架中在 xml 中定义对象 bean ,放到 spring 容器中,当需要用时直接取就是了。开始找了很多注解,以为可以通过扫描实现,最后还是不行,找到引入 xml 方式实现。

Spring boot 项目创建 xml

整个项目如下图,上面是一个 Spring boot 项目,下面是一个公共 jar 。前者依赖了后者。现在要直接以 Autowired方式使用后者的对象。

创建一个 xml ,命名 application-bean.xml 。将想要注入的 bean 设置进去。此 xml 位置在 resources下。写完后应该会提示将这个文件添加到 spring 中。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
    <bean id="testBean" class="com.guozh.TestBean"></bean>
</beans>

我这里已经添加完成,所以提示如下。

不清楚的可以去 Project Structure 看看。实在不知道怎么加,直接将整个删除,然后保存再次全选添加保存即可。

使用Configuration注解配置类

创建一个配置类,这里我命名BeanConfig,全部代码如下:

/**
 * Created by guozhaohui628@gmail.com on 2019/1/9
 * Description:
 */
@Configuration
@ImportResource(locations= {"classpath:application-bean.xml"})
public class BeanConfig {

}

好的 在这里为止就已经可以了。

如果要使用已经配置的对象,直接使用Autowired装配,调用方法即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值