SpringBoot加载mapper.xml的两种方法

SpringBoot加载mapper.xml的两种方法,第1张

(1)在yml里面配置mapper文件的路径

mybatis:

     type-aliases-package: com.entity

     mapper-locations: classpath:mapper/*.xml

(2)在启动类里面添加mapper类的扫描包

@SpringBootApplication

@MapperScan("com.mapper")

public class PlanApplication {}

(1)在pom.xml文件里面配置资源文件加载路径

<build>

<resources>

<resource>

<directory>src/main/java</directory>

<includes>

<include>**/*.properties</include>

<include>**/*.xml</include>

</includes>

<filtering>false</filtering>

</resource>

</resources>

</build>

(2)在yml里面配置实体类的别名

mybatis:

     type-aliases-package: com.entity

(3)在启动类里面添加mapper类的扫描包

@SpringBootApplication

@MapperScan("com.mapper")

public class PlanApplication {}

有时候,要通过自定义XML配置文件来实现一些特定的功能。这里通过例子来说明。

首先,看部分spring加载bean文件的源码:

spring-beans-5.0.6.RELEASE.jar!/org/springframework/beans/factory/xml/PluggableSchemaResolver.class :

spring-beans-5.0.6.RELEASE.jar!/org/springframework/beans/factory/xml/DefaultNamespaceHandlerResolver.class :

可以看出,spring在加载xml文件的时候,会默认读取配置文件 META-INF/spring.schemas 和 META-INF/spring.handlers 。这样,我们就可以在这两个文件添加我们自定义的xml文件格式和xml文件解析处理器。

新建一个Springboot工程,pom如下。

SelfDefineXmlTrial/pom.xml :

然后,新建一个用于测试controller。

com.lfqy.springboot.selfdefxml.controller.SelfDefXmlController :

最后,创建一个Springboot的启动类。

com.lfqy.springboot.selfdefxml.SelfDefXmlApplication :

运行启动之后,浏览器访问 http://localhost:8080/selfdefxml/hello 效果如下:

修改前面提到的配置文件 META-INF/spring.schemas 、 META-INF/spring.handlers ,添加xml格式说明。

META-INF/spring.schemas :

META-INF/spring.handlers :

添加xml格式说明配置文件。

META-INF/selfdef.xsd :

添加自定义xml格式处理器类。

com.lfqy.springboot.selfdefxml.selxmlparse.UserNamespaceHandler :

新增xml格式解析类。

com.lfqy.springboot.selfdefxml.selxmlparse.UserBeanDefinitionParser :

新增自定义xml对应的bean类。

com.lfqy.springboot.selfdefxml.beans.User :

添加自定义xml配置文件读取的相关逻辑。

com.lfqy.springboot.selfdefxml.SelfDefXmlApplication :

到这里,编码就完成了,工程的目录结构如下。

运行之后,控制台输出如下:

这里,通过实现一个启动时自动初始化的一个servlet来实现。

com.lfqy.springboot.selfdefxml.servlet.StartupServlet :

在启动时加载servlet,为了方便区分,这里新写一个启动类。

com.lfqy.springboot.selfdefxml.SelfDefXmlLoadOnStartupApplication

到这里,编码已经完成,工程的目录结构如下:

运行之后,控制台输出如下:

解决方法如下:

1.项目下面有pom.xml文件,要在pom文件下添加2.这个${basedir}的意思是本地路径添加以上代码后即可。还有就是,在别的服务下面的子pom.xml也要添加以上代码,但不同的是,要看好路径。

也就是/?不一样的,自己看看你的文件目录,反正不报错即可。

此功能是每次运行maven工程的时候,会默认编译所有的模块(效率会慢)。


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/7957639.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-12
下一篇2023-04-12

发表评论

登录后才能评论

评论列表(0条)

    保存