amique
amique

Reputation: 2226

Spring boot web war - web-inf/classes/context.xml file not found

When I deploy spring boot based project to tomcat, server is not able to find persistence-context.xml which is under WEB-INF/classes. I receive following error on tomcat console

 java.io.FileNotFoundException: Could not open ServletContext resource [/persistence-context.xml]

I have following structure of Spring boot WS application:

src/main/java/hello/
                   Application.java
                   HelloWebXml.java

src/main/resources/
                   persistence-context.xml

Following are my classes

@ComponentScan("foo.bla.bar")
@ImportResource("classpath:persistence-context.xml")
@Configuration
@EnableAutoConfiguration
public class Application {

    public static void main(final String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Following is the WebXml class.

public class HelloWebXml extends SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
    return application.sources(Application.class);
}
}

Following is my pom.xml file

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.foo.bar</groupId>
<artifactId>bar-ws</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.1.4.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

<properties>
    <start-class>bla.bar.Application</start-class>
</properties>

<build>
    <plugins>
        <plugin> 
            <artifactId>maven-compiler-plugin</artifactId> 
        </plugin>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</project>

I am building a war file of this project. Can anyone please guide me how to fix this? Thanks

Upvotes: 0

Views: 2650

Answers (1)

SparkOn
SparkOn

Reputation: 8946

@ImportResource("classpath:persistence-context.xml")

Will work fine just dont forget to put the persistence-context.xml under the webapp folder as it is considered as the classpath in case of Web Project.

Well in for placing the file under src/main/resources then try reading it this way you will never face path problem in this case.

String pathOfTheResurceFile = Thread.currentThread().getContextClassLoader()
                                    .getResource("yourFileName").getPath();

Upvotes: 1

Related Questions