Spring Boot (二十三)——加载XML配置

前言

在使用springboot的时候一般是极少需要添加配置文件的(application.properties除外),但是在实际应用中也会存在不得不添加配置文件的情况,例如集成其他框架或者需要配置一些中间件等,在这种情况下,我们就需要引入我们自定义的xml配置文件了。

实现

看一个最简单的例子,不用注解,使用xml的方式给容器中注入一个bean:

首先,准备一个bean,不要注解:

public class Hello {
    public void sayHello(){
        System.out.println("hello macay");
    }
}

在resource目录下创建一个bean.xml:

<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 name="hello" class="com.macay.xml.Hello"></bean>
</beans>

创建一个配置类,使用@ImportResource注解加载一个XML:

@Configuration
@ImportResource(value = "classpath:bean.xml")
public class MvcConfig {

}

测试一下,看Hello对象有没有注入容器中:

@SpringBootTest
class XmlApplicationTests {
    @Autowired
    Hello hello;

    @Test
    void contextLoads() {
        hello.sayHello();
    }
}

测试结果如下:
在这里插入图片描述
说明XML文件已加载,Hello对象一杯注入Spring容器中。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot是一个快速开发的框架,提供了很多方便的工具,其中包括Mybatis框架。在使用Mybatis框架时,需要将Mapper.xml文件加载到应用程序中。 在Spring Boot中,可以使用@MapperScan注解将Mapper接口的包路径配置到扫描器中,然后使用@Mapper注解将Mapper接口注入到IOC容器中。但是,这种方式只会自动扫描Mapper接口,对于Mapper.xml文件需要手动进行配置。 首先,需要在application.properties或application.yml文件中配置Mapper.xml文件的路径,例如: mybatis.mapper-locations=classpath:mapper/*.xml 然后,需要创建SqlSessionFactoryBean并为其设置DataSource和Mapper.xml文件的位置: @Configuration public class MybatisConfig { @Value("${mybatis.mapper-locations}") private String mapperLocations; @Autowired private DataSource dataSource; @Bean public SqlSessionFactoryBean sqlSessionFactory() throws Exception { SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(dataSource); sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver() .getResources(mapperLocations)); return sessionFactory; } } 在创建完SqlSessionFactoryBean后,需要在Mapper接口中使用@Mapper注解,并通过@Autowired注入SqlSessionFactoryBean,例如: @Mapper public interface UserMapper { @Autowired SqlSessionFactory sqlSessionFactory; // ... } 最后,在需要使用Mapper接口的地方,可以直接将Mapper接口注入到Spring Bean中,并使用@Autowired注入即可,例如: @RestController public class UserController { @Autowired private UserMapper userMapper; // ... } 通过这种方式,就可以在Spring Boot中方便地加载Mapper.xml文件,并使用Mybatis框架完成相应的数据操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值