I can not generate proper WAR file for Tomcat.
I am using MAVEN 3.6.1, Java 12.0.1 and IDE Eclipse. My app is working fine when I run it in eclipse (Run as > Spring Boot App) but the problem is when I am trying to run my WAR file after generate it.
I am doing java -jar .war and I am getting:
Error: Could not find or load main class com.blw.linemanager.Application
Caused by: java.lang.ClassNotFoundException: com.blw.linemanager.Application
I was googling and reading stackoverflow cause I found many post about it but still can not run it. What I am doing wrong?
After some reading I figured out that I have some how configure maven-war-plugin (am I right?) and in pom I did some changes but it does not help.
<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>bwl</groupId>
<artifactId>LineManager</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.1.3.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-utils</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<properties>
<start-class>com.blw.linemanager.Application</start-class>
<maven.compiler.source>12</maven.compiler.source>
<maven.compiler.target>12</maven.compiler.target>
</properties>
<build>
<finalName>LineManager</finalName>
<outputDirectory>${project.build.directory}</outputDirectory>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<release>12</release>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>copy-resources</id>
<phase>validate</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/META-INF</outputDirectory>
<resources>
<resource>
<directory>${basedir}/src/main/resources/META-INF</directory>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<archive>
<manifest>
<classpathPrefix>${project.build.directory}/WEB-INF/classes</classpathPrefix>
<addClasspath>true</addClasspath>
<mainClass>com.blw.linemanager.Application</mainClass>
</manifest>
<manifestFile>${project.build.directory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>
Also because on the beginning I was getting error 'no main manifest attribute' I add it and now it looks like this
Manifest-Version: 1.0
Created-By: Apache Maven ${maven.version}
Build-Jdk: ${java.version}
Is my way of think wrong? Should I be able to run .war file as java -jar .war or this is missunderstanding?
#SpringBootApplication
public class Application extends org.springframework.boot.web.support.SpringBootServletInitializer {
public static void main(String [] args) {
SpringApplication app = new SpringApplication(Application.class);
app.run(args);
}
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(Application.class);
}
}
It is better to get a working spring boot application from here to avoid versions conflicts and the like.
For a war-file deployment (into a local tomcat for example), your application must extend SpringBootServletInitializer:
#SpringBootApplication
public class SpringBootTomcatApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(SpringBootTomcatApplication.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(SpringBootTomcatApplication.class);
}
}
Change in your pom the packaging to war.
<packaging>war</packaging>
To generate a war-file you need just the spring-boot-maven-plugin:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
And yes you don't need the maven-war-plugin. Just for testing purposes let's annotate our application with #RestController and introduce a simple endpoint:
#RestController
#SpringBootApplication
public class SpringBootTomcatApplication extends SpringBootServletInitializer {
...
#RequestMapping(value = "/")
public String hello() {
return "Hello World from Tomcat";
}
}
In the Local terminal (in eclipse Ctrl+Alt+T) just enter mvn package than copy the generated war-file from target folder, paste it under the webapps folder of your local Tomcat, request http://localhost:8080/{your-application-name} and you should see the message Hello World from Tomcat.
Now you can add the dependencies you need and continue coding.
Add packaging type with version detail in pom.xml like
<packaging>jar</packaging>
or
<packaging>war</packaging>
Then, append build tag to define name of jar / war like,
<build>
<finalName>YOUR-APP_NAME</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Then, run your application with goal
clean package
to create jar/war in target folder.
Rename your war file to ROOT like ROOT.war
Last step to copy your created jar/war in tomcat webapps folder and start tomcat.
Related
I am working with one spring boot multi module maven project, here i am getting below exception, every time when i run application it fails for different different files.
The bean 'evServiceCpeRepository' could not be registered. A bean with that name has already been defined
this project has three module sbill , amr and executable ,
this all classes i have in sbill module... amr module is empty it has just one controller and in amr module pom file i have added dependency for sbill module because amr module can access classes of sbill.
executable module just contain spring boot main class , apart from that no any classes this module is executable module.
#SpringBootApplication
#ComponentScan(basePackages = { "com"})
#EntityScan(basePackages = { "com"})
#EnableJpaRepositories(basePackages = { "com"})
public class MainClass {public static void main(String[] args) {
SpringApplication.run(MainClass.class, args);
}}
pom of executable module
<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>
<parent>
<groupId>com.sbill</groupId>
<artifactId>sbill-wrapper</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<packaging>war</packaging>
<artifactId>executable</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.sbill</groupId>
<artifactId>sbill</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.sbill</groupId>
<artifactId>amr</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- Adding plugin of mavan resource to copy dist folder for war -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<id>copy-resources</id>
<phase>validate</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/classes/static/</outputDirectory>
<resources>
<resource>
<directory>../web/dist</directory>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
I am able to resolve this issue myself...
issue was related to #EnableJpaRepositories(basePackages = { "com"}) annotation. this annotation i have put in Mainclass.java file and this annotation was already there in one configuration file of module sbill.
so two times spring was trying to create beans that's why it was failing.
i removed that annotation from another configuration file and its works perfectly fine.
This might be a weird question but I am curious about this:
I want to create a Java EE Web Project, that I can package into a JAR file (<packaging>jar</packaging> instead of <packaging>war</packaging>).
In other words, I want to include the Java EE web server inside a JAR (built by maven).
Inside the WebServer I want to use Servlets like I can use them when I package it to a WAR file but without requireing the devices that execute the JAR to have a Web server installed where they can deploy my JAR.
I want something like an executeable JAR that contains the server and runs it without the need to install something else.
Is there a (ideally light-weight) server that works within a JAR file or any other possibility to create a JAR file like this?
If you want to use vanilla Java EE, you can use an Embedded Jetty Server or Embedded Tomcat Server:
Here is an example with Embedded Tomcat and Maven:
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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.company</groupId>
<artifactId>app</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>12</maven.compiler.source>
<maven.compiler.target>12</maven.compiler.target>
<servlet.version>3.1.0</servlet.version>
<jsf.version>2.2.19</jsf.version>
<tomcat.version>9.0.21</tomcat.version>
</properties>
<dependencies>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>${jsf.version}</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>${jsf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-el</artifactId>
<version>${tomcat.version}</version>
</dependency>
</dependencies>
<build>
<finalName>app</finalName>
<resources>
<resource>
<directory>src/main/webapp</directory>
<targetPath>META-INF/resources</targetPath>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>12</source>
<target>12</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<finalName>app-${project.version}</finalName>
<archive>
<manifest>
<mainClass>org.company.app.Application</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
mainClass:
package org.company.app;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.StandardRoot;
import java.io.File;
public class Application {
public static void main(final String[] args) throws Exception {
final String webappPath = new File("src/main/webapp").getAbsolutePath();
final Tomcat tomcat = new Tomcat();
final StandardContext ctx = (StandardContext) tomcat.addWebapp("/", webappPath);
System.out.println(ctx
);
// Declare an alternative location for your "WEB-INF/classes" dir
// Servlet 3.0 annotation will work
final String targetClassesPath = new File("target/classes").getAbsolutePath();
final WebResourceRoot resources = new StandardRoot(ctx);
resources.addPreResources(new DirResourceSet(//
resources, "/WEB-INF/classes", //
targetClassesPath, "/"));
ctx.setResources(resources);
tomcat.start();
tomcat.getServer().await();
}
}
and the rest as usual java ee development
I'm using Maven and Vert.x to create an application.
Everything is working fine while I run it in my IDE (IntelliJ) but I can't make it work using command line.
I have a Launcher class that deploy some verticles but the problem is the same with all my verticles.
So far here is what I've tried:
vertx run Launcher.java
vertx run com.packagename.Launcher.java
// user-content-service-0.1.jar create via: mvn clean package
run com.packagename.Launcher.java -cp target\user-content-service-0.1.jar
As error I get this:
.../path/Launcher.java:8: error: cannot find symbol
private static final Logger logger = logManager.getLogger(Launcher.class);
symbol: variable LogManager
location: class com.packagename.Launcher
java.lang.RuntimeException: Compilation failed
...
The issue seems to come from the fact that the compiler is not able to find dependancies
Here is what my pom.xml looks like:
<?xml version="1.0" encoding="UTF-8"?>
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.packagename</groupId>
<artifactId>user-content-service</artifactId>
<packaging>jar</packaging>
<version>0.1</version>
<name>Project - user-content-service</name>
<url>http://maven.apache.org</url>
<properties>
<vertx.version>[3.5.0,3.6)</vertx.version>
<java.version>1.8</java.version>
<maven-compiler-plugin.version>3.3</maven-compiler-plugin.version>
<log4j.version>[2.10.0,2.11)</log4j.version>
<junit.version>4.12</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-core</artifactId>
<version>${vertx.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-unit</artifactId>
<version>${vertx.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-dynamodb</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-config</artifactId>
<version>${vertx.version}</version>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-web</artifactId>
<version>${vertx.version}</version>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-web-client</artifactId>
<version>${vertx.version}</version>
</dependency>
<dependency>
<groupId>guru.nidi.raml</groupId>
<artifactId>raml-tester</artifactId>
<version>0.9.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
And that's my Launcher.java file:
package com.packagename;
import io.vertx.core.AbstractVerticle; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger;
public class Launcher extends AbstractVerticle {
private static final Logger logger = LogManager.getLogger(Launcher.class);
#Override
public void start() {
vertx.deployVerticle("com.packagename.DynamoDBVerticle", logRes -> {
if (logRes.succeeded()) {
vertx.deployVerticle("com.packagename.UploaderVerticle", uploaderRes -> {
if (uploaderRes.succeeded()) {
vertx.deployVerticle("com.packagename.ServerVerticle", serverRes -> {
if (!serverRes.succeeded()) {
logger.error("Could not start server");
}
});
}
else {
logger.error("Could not start uploader");
}
});
}
else {
logger.error("Could not start Dynamo");
}
});
} }
Any clue what could I be doing wrong here ?
Thanks !
You are having a classpath issue; because you package your jarfile with maven-jar in the package phase, you are only getting that in the build directory; if you want to run on the command-line with java -jar, you should create a fat-jar (aka uber-jar, a jar file specifically packaged in order for it to contain your classes and all dependencies declared in the pom file).
You can add the maven-shade-plugin to do that in the package phase, ie:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.3</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<manifestEntries>
<Main-Class>io.vertx.core.Launcher</Main-Class>
<Main-Verticle>com.packagename.Launcher</Main-Verticle>
</manifestEntries>
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/services/io.vertx.core.spi.VerticleFactory</resource>
</transformer>
</transformers>
<artifactSet/>
<outputFile>${project.build.directory}/${project.artifactId}-${project.version}-fat.jar</outputFile>
</configuration>
</execution>
</executions>
</plugin>
Note: you have a class name clash between the vert.x Launcher (used as Main-Class, in the fat-jar), and your own Launcher (which is actually a Verticle): I'd suggest to rename it.
After maven package, you will be then able to do:
java -jar target/user-content-service-0.1-fat.jar
Check in the vert.x samples for more information.
I am trying to create executable JAR file for my spring boot application.
To achieve this spring-boot-maven-plugin has been used with main class specified and packaging to jar.
Unfortunately after running output JAR file i receive java.lang.ClassNotFoundException pointing to my main class.
Below is my pom.xml and main class. Thanks in advance for help.
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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>com.test</groupId>
<artifactId>interflight</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>interflight</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<feign-gson.version>7.2.1</feign-gson.version>
<spring-cloud.version>Edgware.SR1</spring-cloud.version>
<gson.version>2.8.0</gson.version>
<assertj-core.version>3.8.0</assertj-core.version>
<startClass>com.test.interflight.configuration.InterflightApplication</startClass>
</properties>
<dependencies>
<!--External dependencies-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
<groupId>com.netflix.feign</groupId>
<artifactId>feign-gson</artifactId>
<version>${feign-gson.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--Test dependencies-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<finalName>${project.artifactId}</finalName>
<layout>ZIP</layout>
<mainClass>com.test.interflight.configuration.InterflightApplication</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
Output error:
$ java -jar interflight.jar
Exception in thread "main" java.lang.ClassNotFoundException: com.test.interfl
ight.configuration.InterflightApplication
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at org.springframework.boot.loader.LaunchedURLClassLoader.loadClass(Laun
chedURLClassLoader.java:94)
at java.lang.ClassLoader.loadClass(Unknown Source)
at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner
.java:46)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
at org.springframework.boot.loader.PropertiesLauncher.main(PropertiesLau
ncher.java:587)
Main class:
#SpringBootApplication
#ComponentScan(basePackages = {"com.test.interflight.controller", "com.test.interflight.implementation.*"})
#EnableFeignClients(basePackages = {"com.test.interflight.api.restclient"},
defaultConfiguration = FeignConfiguration.class)
public class InterflightApplication {
public static void main(String[] args) {
SpringApplication.run(InterflightApplication.class, args);
}
}
Short answer:
Looks like you're using the ZIP layout when you should be using the JAR layout. Change <layout>ZIP</layout> to <layout>JAR</layout> in your Spring Boot maven plugin declaration.
Longer answer:
Take a look at the docs which describe the ZIP layout as:
ZIP (alias to DIR): similar to the JAR layout using
PropertiesLauncher.
And of which the PropertiesLauncher is described in the docs as:
Launcher for archives with user-configured classpath and main class
via a properties file...
Looks in various places for a properties file to extract loader settings, defaulting to application.properties... No default, but will fall back to looking for a Start-Class in a MANIFEST.MF
If you want it to be user specified in your Jar file, specify (or check and see if you have one already) in the meta-inf folder of your Jar, or specify the property yourself.
After several days dealing with various plugins, finally I could make a fat jar (spring boot) with externalize config files everywhere I wanted to be. You can use the following plugins:"config" is the path for your config files next to the jar file.
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<finalName>jarfilename</finalName>
<mainClass>com.start.YourStarter</mainClass>
<layout>ZIP</layout>
</configuration>
<executions>
<execution>
<phase>install</phase>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/log4j.xml</exclude>
<exclude>deploy/**</exclude>
<exclude>**/*.properties</exclude>
<exclude>**/*.txt</exclude>
</excludes>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.start.YourStarter</mainClass>
<useUniqueVersions>false</useUniqueVersions>
</manifest>
<manifestEntries>
<Class-Path>config/</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
I am new to spring and maven. I have a simple hello world project using Spring . The project builds successfully but i face the following error at runtime:
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/context/ApplicationContext
This is the main app: App.java
package com.test.SpringMaven2;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
System.out.println( "Hello World!" );
ApplicationContext context = new AnnotationConfigApplicationContext(HelloWorldConfig.class);
HelloWorld hello = (HelloWorld) context.getBean("helloWorld");
hello.setName("Adnan");
hello.getName();
}
}
This is the HelloWorld bean
package com.test.SpringMaven2;
public class HelloWorld{
private String name;
public void setName(String name){
this.name = name;
}
public void getName(){
System.out.println("Hello, " + name);
}
}
This is the annotation based configuration file:
package com.test.SpringMaven2;
import org.springframework.context.annotation.*;
#Configuration
public class HelloWorldConfig{
#Bean
public HelloWorld helloWorld(){
return new HelloWorld();
}
}
This is my pom.xml
<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>com.test</groupId>
<artifactId>SpringMaven2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringMaven2</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
</dependencies>
</project>
I am running the following command in CMD to run the application:
java -cp {nameofresultjarfile} com.test.SpringMaven2.App
But getting the error messsage above
Any advice?
Thanks
Your pom.xml creates a jar file which contains only the classes defined in your project. But all the other dependencies (spring-core, spring-context-support) which are required by your application aren't included.
If your application is started within eclipse, eclipse integrates these required jar files to the classpath of the application and so it is able to run.
If your application is started from CMD the spring classes can't be found in the classpath and you get a java.lang.NoClassDefFoundError.
It's possible to name all the required jars manually when the application is started from CMD (classpath), but is much easier to created a so called self contained jar file, which has all of them already included. This can be done using maven-assembly-plugin.
An example how to create a self contained jar file can be found here.
The application in a self contained jar can be started now from CMD:
java -jar name_of_your_project-jar-with-dependencies.jar
I was getting the same error when running from Intellij as a main class (In Spring Boot project)
After opening Module settings, In the Deopendencies tab I saw that for spring-context for some reason the scope was provided, changing to compile/ even removing the scope fixed the issue for for me
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>## Put your desired version here ##</version>
</dependency>
In my similar case both #jaysee answer or:
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>com.example.MyMainClass </mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
or
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.5.0</version>
helped.
The below fixed similar issue for me.
build plugins section should be put right after /dependencies:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.5.4</version>
<configuration>
<layout>ZIP</layout>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
I was facing the same issue. I am using the intellij 2021 but the above solution didn't work. Also in eclipse it was working fine . The solution that worked for me was:
1)Go to edit run/debug configuraiton
2)Modify option
3)Check "include dependency with provided scope"