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

版权声明:http://guozh.net/ 《=== 秘密哦 https://blog.csdn.net/guozhaohui628/article/details/86610183

最近一个项目 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 [email protected] on 2019/1/9
 * Description:
 */
@Configuration
@ImportResource(locations= {"classpath:application-bean.xml"})
public class BeanConfig {

}

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

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

猜你喜欢

转载自blog.csdn.net/guozhaohui628/article/details/86610183