SpringBoot导入XML

来源:互联网 发布:mysql导出数据库 编辑:程序博客网 时间:2024/05/21 07:14

项目如图所示

入口类是SpringBootTestApplication,项目正常情况下只能扫描入口类的当前包及其子包,即可以扫描到Student类,却扫描不到Good类


编写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.xsd">   <bean id="good" class="com.example.demo2.Good">   </bean></beans>

XML的作用是把Good加入IOC容器

编写config类引入xml文件

在入口类同包或者子包下创建一个Config类,这样在类上加上注解才能加入IOC容器


package com.example.demo.config;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.ImportResource;/**   *   * classpath路径:locations={"classpath:classpath:context.xml","classpath:classpath:context2.xml"}   * file路径: locations = {"file:d:/test/classpath:context.xml"}; */ @Configuration @ImportResource(locations={"classpath:context.xml"}) public class Config {}

测试结果