我正在开发一个项目(spring boot),我必须使用 maven jaxb2 插件将 xml 文件转换为 Java 类。我正在关注这个链接:
生成类问题是当我尝试解码xml时出现此错误:
资源 ServletContext 资源 [/xsd/MX_seev_031_001_05. xsd] 不存在
这是我的 application.properties:
context.path =xml.swift.spring.com
schema.location= xsd/MX_seev_031_001_05.xsd
这是我的配置 bean:
@Bean
public Jaxb2Marshaller createJaxb2Marshaller(@Value("${context.path}") final String contextPath,
@Value("${schema.location}") final Resource schemaResource){
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath(contextPath);
marshaller.setSchema(schemaResource);
Map<String, Object> properties = new HashMap<>();
properties.put(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setMarshallerProperties(properties);
return marshaller;
xsd 文件位于 src/main/resources/xsd 下,这是我的 pom.xml:
<plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<version>0.12.1</version>
<executions>
<execution>
<id>add-source-for-demoapp</id>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<schemaDirectory>${project.basedir}/src/main/resources/xsd</schemaDirectory>
<schemaIncludes>
<include>*.xsd</include>
</schemaIncludes>
<!-- Other configuration options-->
</configuration>
</execution>
</executions>
我错过了什么?
谢谢。
最佳答案
当我开始在 pom.xml 中使用 spring-oxm(我也有 spring-boot-starter-data-jpa)之外的 spring-boot-starter-data-rest 时,我遇到了基本相同的问题。
问题在于您的第二个自动注入(inject)参数;
@Value("${schema.location}") 最终资源 schemaResource
所以而不是
@Bean
public Jaxb2Marshaller createJaxb2Marshaller(@Value("${context.path}") final String contextPath, @Value("${schema.location}") final Resource schemaResource){
//...
marshaller.setSchema(schemaResource);
//...
}
在下面做;
@Bean
public Jaxb2Marshaller createJaxb2Marshaller(@Value("${context.path}") final String contextPath, @Value("${schema.location}") final String schemaLocation){
//...
Resource schemaResource = new ClassPathResource(schemaLocation);
marshaller.setSchema(schemaResource);
//...
}
试一试,它会起作用的。
关于spring-boot - Resource ServletContext 资源不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43429514/