Gradle Spring Boot Project Cannot Run From IDEA [duplicate] - spring-boot

This question already has answers here:
NoClassDefFoundError after IntelliJ IDEA upgrade
(3 answers)
Closed 5 years ago.
I am struggling to set up the spring boot project that i have imported in intelliJ IDEA 2016 1.4.
Every time i run . I get the below Exception:
Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/boot/SpringApplication
at com.patientConnect.DemoApplication.main(DemoApplication.java:24)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 6 more
My gradle settings (linked gradle projects,user gradle wrapper ) all looks good.
package com.Demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class DemoApplication {
public DemoApplication() {
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
build.gradle:
buildscript {
repositories {
mavenLocal()
mavenCentral()
maven {
url 'https://plugins.gradle.org/m2/'
}
}
dependencies {
classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.4.2.RELEASE'
classpath 'gradle.plugin.com.jamesward:atom-gradle-plugin:0.0.1'
}
}
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
compile 'org.springframework.boot:spring-boot-starter-parent:1.5.4.RELEASE'
compile 'org.springframework.boot:spring-boot-starter-web'
compile 'org.springframework.boot:spring-boot-devtools'
compile 'org.springframework.boot:spring-boot-starter-security'
compile 'org.springframework.security.oauth:spring-security-oauth2'
compile 'org.apache.httpcomponents:httpclient'
compile 'org.springframework.boot:spring-boot-starter-data-jpa'
compile 'org.postgresql:postgresql'
compile 'org.springframework.boot:spring-boot-starter-jdbc'
compile 'org.hibernate:hibernate-entitymanager'
}
allprojects {
sourceCompatibility = 1.8
targetCompatibility = 1.8
}
import org.gradle.internal.os.OperatingSystem
task devClasses(type: Exec) {
if (OperatingSystem.current().isWindows())
commandLine 'gradlew', '-t', 'classes'
else
commandLine './gradlew', '-t', 'classes'
}
task devBootRun(type: Exec) {
if (OperatingSystem.current().isWindows())
commandLine 'gradlew', 'bootRun'
else
commandLine './gradlew', 'bootRun' //, '--debug-jvm'
}
import java.util.concurrent.*
task dev() << {
def devClassesFuture = Executors.newSingleThreadExecutor().submit({ devClasses.execute() } as Callable)
def devBootRunFuture = Executors.newSingleThreadExecutor().submit({ devBootRun.execute() } as Callable)
devClassesFuture?.get()
devBootRunFuture?.get()
}
task stage {
dependsOn build
}

Try deleting your SpringBoot dependency on your computer.
It will be located at ~/.gradle/caches/modules-2/files-2.1/org.springframework.boot Assuming you kept your gradle dependencies in the default location.
rm -rf ~/.gradle/caches/modules-2/files-2.1/org.springframework.boot
or to delete all dependencies (Just to be sure if no other dependencies is corrupted)
rm -rf ~/.gradle/caches/modules-2/files-2.1/*
then to re-download
gradle build --refresh-dependencies

Related

org.spockframework.runtime.SpockEngine Unable to get public no-arg constructor encountered while upgrading Groovy and Spock

Using Gradle 7.1.1, Java 16, Groovy 3.0.8 and Spock 2.0-groovy-3.0
I'm getting this error when running ./gradlew clean test
Caused by: java.util.ServiceConfigurationError: org.junit.platform.engine.TestEngine: org.spockframework.runtime.SpockEngine Unable to get public no-arg constructor
at java.base/java.util.ServiceLoader.fail(ServiceLoader.java:582)
at java.base/java.util.ServiceLoader.getConstructor(ServiceLoader.java:673)
at java.base/java.util.ServiceLoader$LazyClassPathLookupIterator.hasNextService(ServiceLoader.java:1232)
at java.base/java.util.ServiceLoader$LazyClassPathLookupIterator.hasNext(ServiceLoader.java:1264)
at java.base/java.util.ServiceLoader$2.hasNext(ServiceLoader.java:1299)
at java.base/java.util.ServiceLoader$3.hasNext(ServiceLoader.java:1383)
at java.base/java.lang.Iterable.forEach(Iterable.java:74)
at org.junit.platform.launcher.core.LauncherFactory.create(LauncherFactory.java:95)
at org.junit.platform.launcher.core.LauncherFactory.create(LauncherFactory.java:75)
at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:97)
at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
... 25 more
Caused by: java.lang.NoClassDefFoundError: org/junit/platform/engine/support/discovery/SelectorResolver
at java.base/java.lang.Class.getDeclaredConstructors0(Native Method)
at java.base/java.lang.Class.privateGetDeclaredConstructors(Class.java:3305)
at java.base/java.lang.Class.getConstructor0(Class.java:3510)
at java.base/java.lang.Class.getConstructor(Class.java:2238)
at java.base/java.util.ServiceLoader$1.run(ServiceLoader.java:660)
at java.base/java.util.ServiceLoader$1.run(ServiceLoader.java:657)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:554)
at java.base/java.util.ServiceLoader.getConstructor(ServiceLoader.java:668)
... 36 more
Caused by: java.lang.ClassNotFoundException: org.junit.platform.engine.support.discovery.SelectorResolver
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:636)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:182)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:519)
... 44 more
This is the build.gradle for the module where error is reported:
dependencies {
implementation 'io.rest-assured:rest-assured'
implementation 'org.yaml:snakeyaml'
implementation 'com.fasterxml.jackson.core:jackson-databind'
testImplementation 'org.junit.jupiter:junit-jupiter'
testImplementation('org.spockframework:spock-core') {
transitive = false
}
}
Parent module build.gradle file:
ext {
jupiterVersion = '5.7.2'
}
jar.enabled = false
subprojects {
apply plugin: 'java'
apply plugin: 'groovy'
apply plugin: 'codenarc'
jar.enabled = true
codenarc {
toolVersion = '1.4'
reportFormat = 'html'
configFile = new File('../../tool/codenarc/groovy-ruleset.groovy')
}
dependencyManagement {
imports {
mavenBom("org.springframework.boot:spring-boot-dependencies:2.5.1") {
bomProperties(['selenium.version' : '3.141.59',
'rest-assured.version': '4.1.1'])
}
}
dependencies {
dependency 'org.codehaus.groovy.modules.http-builder:http-builder:0.7.1'
dependency 'org.spockframework:spock-core:2.0-groovy-3.0'
dependency 'com.athaydes:spock-reports:2.0-groovy-3.0'
dependency 'com.codeborne:selenide:5.3.1'
dependency 'org.hamcrest:hamcrest:2.1'
dependencySet(group: 'org.junit.jupiter', version: jupiterVersion) {
entry 'junit-jupiter'
entry 'junit-jupiter-api'
}
dependencySet(group: 'org.slf4j', version: '1.7.28') {
entry 'jcl-over-slf4j'
entry 'jul-to-slf4j'
}
dependencySet(group: 'org.aspectj', version: '1.9.4') {
entry 'aspectjrt'
entry 'aspectjweaver'
}
dependency 'io.rest-assured:rest-assured:4.1.1'
dependency 'org.postgresql:postgresql:42.2.8'
dependency 'org.yaml:snakeyaml:1.25'
dependency 'org.apache.poi:poi-ooxml:4.1.1'
dependency 'com.opencsv:opencsv:4.0'
dependency 'org.junit.platform:junit-platform-launcher:1.4.0'
}
}
test {
useJUnitPlatform()
}
}
Any help would be appreciated.
PS. This was working with Java 11, Groovy 2.5 and Spock 1.3-groovy-2.5
Have you added useJUnitPlatform()?
https://github.com/spockframework/spock-example/blob/master/build.gradle#L34
test {
useJUnitPlatform()
}
It was a problem with the parent project's build.gradle file.
I recently upgraded the spring boot version to 2.5.1.
After updating this entry in the build.gradle file the error went away.
imports {
mavenBom("org.springframework.boot:spring-boot-dependencies:2.5.1") {
bomProperties(['selenium.version' : '3.141.59',
'rest-assured.version': '4.1.1'])
}
}

slf4j LoggerFactory class definition not found with Gradle

I'm trying to build and run a Spark webserver that uses slf4j logging in IntelliJ. It builds fine (also in IntelliJ) on the computer that was used to originally add logging, but not on my machine.
Here's the full build.gradle file (see project(':webserver') for the part that uses the logger:
buildscript {
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath "gradle.plugin.com.avast.gradle:docker-compose-gradle-plugin:0.3.27"
}
}
subprojects {
repositories {
mavenLocal()
mavenCentral()
jcenter()
}
apply plugin: "java"
apply plugin: "idea"
apply plugin: "checkstyle"
apply plugin: "pmd"
apply plugin: "findbugs"
apply plugin: "application"
apply plugin: "com.avast.gradle.docker-compose"
checkstyle {
configFile = "../config/checkstyle/checkstyle.xml" as File
toolVersion = "6.0"
}
}
project(':webserver') {
mainClassName = "org.passport.webserver.WebServer"
dependencies {
compile project(':core')
compile "com.sparkjava:spark-core:2.6.0"
testCompile 'junit:junit:4.12'
compile group: 'org.json', name: 'json', version: '20090211'
compile group: 'org.slf4j', name: 'slf4j-log4j12', version: '1.6.1'
}
sourceSets {
main {
java {
srcDir 'src/main/java/'
}
}
}
}
project(':customsUI') {
mainClassName = "org.passport.customsui.CustomsUI"
dependencies {
compile project(':core')
testCompile 'junit:junit:4.12'
}
sourceSets {
main {
java {
srcDir 'src/main/java/'
}
}
}
}
project(':handlerUI') {
mainClassName = "org.passport.handlerui.HandlerUI"
dependencies {
compile project(':core')
testCompile 'junit:junit:4.12'
}
sourceSets {
main {
java {
srcDir 'src/main/java/'
}
}
}
}
project(':core') {
mainClassName = "org.passport.core.PassPortChaincode"
dependencies {
compile 'io.grpc:grpc-all:0.13.2'
compile 'commons-cli:commons-cli:1.3.1'
compile 'org.glassfish:javax.json:1.1.0-M1'
compile files('lib/shim-client-1.0.jar')
testCompile 'junit:junit:4.12'
}
sourceSets {
main {
java {
srcDir 'src/main/java/'
}
}
}
}
Here's the code that uses the logger:
package org.passport.webserver;
import org.passport.webserver.endpoints.ContainerClaimDao;
import org.passport.webserver.endpoints.PackageClaimDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static spark.Spark.before;
import static spark.Spark.get;
import static spark.Spark.path;
import static spark.Spark.post;
/**
* The server matches requests (routs) and calls the appropriate endpoints.
*/
public final class Server {
private static Logger logger = LoggerFactory.getLogger(Server.class);
private static ContainerClaimDao containers = new ContainerClaimDao();
private static PackageClaimDao packages = new PackageClaimDao();
private Server() {
}
/**
* Starts the router.
* #param args run arguments
*/
public static void main(String[] args) {
path("/containers/:container-id", () -> {
before("/*", (q, a) -> logger.info("Received api call: " + q.url() + "."));
post("", (request, response) -> containers.add(request, response));
get("/container-claims", (request, response) -> containers.get(request, response));
get("/package-claims", (request, response) -> packages.get(request, response));
});
}
}
And here's the error I get:
"C:\Program Files\Java\jdk1.8.0_91\bin\java" -Didea.launcher.port=7534 "-Didea.launcher.bin.path=C:\Program Files (x86)\JetBrains\IntelliJ IDEA 2016.2.4\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_91\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_91\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_91\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_91\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_91\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_91\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_91\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_91\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_91\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_91\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_91\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_91\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_91\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_91\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_91\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_91\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_91\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_91\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_91\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_91\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_91\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_91\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_91\jre\lib\rt.jar;C:\Users\lover\repositories\passport\webserver\build\classes\main;C:\Program Files (x86)\JetBrains\IntelliJ IDEA 2016.2.4\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain org.passport.webserver.Server
Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
at org.passport.webserver.Server.<clinit>(Server.java:18)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:123)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 4 more
I've looked at several questions on StackOverflow, but none seem to solve the problem:
java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory - I'm building with gradle, don't think I should have to download/ put some jar in my classpath
ClassNotFoundException: org.slf4j.LoggerFactory - Same as above
NoClassDefFoundError: org/slf4j/Logger - Again jar stuff
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory - I'm not sure whether "fat jars" / ShadowJar apply, and not sure how to modify my build file to use them
NoClassDefFoundError: org/slf4j/LoggerFactory while creating a runnable *.jar with gradle - I've tried refreshing gradle several times, restarting IntelliJ, and even restarting my restarting my computer
Gradle Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory - See below
I've tried the following dependencies:
compile group: 'org.slf4j', name: 'slf4j-log4j12', version: '1.6.1'
compile 'org.slf4j:slf4j-api:1.7.24' and compile 'org.slf4j:slf4j-simple:1.7.24'
compile group: 'org.slf4j', name: 'slf4j-simple', version: '1.6.1'
None of this seems to make a difference. Any ideas?
If you're using Gradle add these 2 lines to your build.gradle dependencies to use Spark 2.6.0
compile "com.sparkjava:spark-core:2.6.0"
compile group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.21'
I ended up deleting my Gradle cache (.gradle folder) and re-downloading everything, which solved the problem.

Failing to run .WAR using java -jar

On an early stage of development of my Spring Boot project I was used to run the application using java -jar build\libs\online_store-0.1.0.jar. Now I need to deliver a WAR. I followed the links below to build a deployable WAR file with Gradle. After that I was able to deploy the resulting built file on Tomcat 8 webapp directory and it is working fine. But I also need to run the embedded server using java -jar. Every time I try to do it (java -jar build\libs\online_store-0.1.0.war) I get a FileNotFoundException related to some missing dependency JAR (please see the stack trace below). After I add the corresponding dependency to the requiresUnpack option the error message changes but I am afraid I will never finish adding dependencies. What am I missing to get the WAR file both deployable and runnable by java -jar? Thanks in advance.
requiresUnpack = [ "org.webjars:less", "org.webjars:jshint", "org.webjars:emberjs",
"org.webjars:handlebars", "org.webjars:coffee-script", "org.webjars:jslint", "org.webjars:json2",
"org.webjars:jquery", "org.webjars:handlebars", "org.slf4j:slf4j-api"
]
http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-create-a-deployable-war-file
http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#build-tool-plugins-gradle-packaging
Snippet of stack trace:
Caused by: java.lang.RuntimeException: java.io.FileNotFoundException: C:\Users\hcorzo\workspace\online_mvp\online_store\build\libs\online_store-0.1.0.war!\WEB-INF\lib\validate.js-0.8.0.jar (The system cannot find the path specified)
at org.webjars.urlprotocols.JarUrlProtocolHandler.getAssetPaths(JarUrlProtocolHandler.java:54)
at org.webjars.WebJarAssetLocator.getAssetPaths(WebJarAssetLocator.java:91)
at org.webjars.WebJarAssetLocator.getFullPathIndex(WebJarAssetLocator.java:121)
at org.webjars.WebJarAssetLocator.<init>(WebJarAssetLocator.java:152)
at org.springframework.web.servlet.resource.WebJarsResourceResolver.<init>(WebJarsResourceResolver.java:52)
at org.springframework.web.servlet.config.annotation.ResourceChainRegistration.getResourceResolvers(ResourceChainRegistration.java:108)
at org.springframework.web.servlet.config.annotation.ResourceHandlerRegistration.getRequestHandler(ResourceHandlerRegistration.java:164)
at org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry.getHandlerMapping(ResourceHandlerRegistry.java:113)
at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.resourceHandlerMapping(WebMvcConfigurationSupport.java:409)
at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration$$EnhancerBySpringCGLIB$$7c82d476.CGLIB$resourceHandlerMapping$33(<generated>)
at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration$$EnhancerBySpringCGLIB$$7c82d476$$FastClassBySpringCGLIB$$7c23c9ca.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356)
at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration$$EnhancerBySpringCGLIB$$7c82d476.resourceHandlerMapping(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
... 25 more
Caused by: java.io.FileNotFoundException: C:\Users\hcorzo\workspace\online_mvp\online_store\build\libs\online_store-0.1.0.war!\WEB-INF\lib\validate.js-0.8.0.jar (The system cannot find the path specified)
at java.util.zip.ZipFile.open(Native Method)
at java.util.zip.ZipFile.<init>(Unknown Source)
at java.util.zip.ZipFile.<init>(Unknown Source)
at java.util.jar.JarFile.<init>(Unknown Source)
at java.util.jar.JarFile.<init>(Unknown Source)
at org.webjars.urlprotocols.JarUrlProtocolHandler.getAssetPaths(JarUrlProtocolHandler.java:36)
... 43 more
And this is my build.gradle file:
buildscript {
repositories {
mavenCentral()
jcenter()
maven { url 'http://dl.bintray.com/sbuettner/maven' }
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.3.RELEASE")
classpath 'ro.isdc.wro4j.gradle:wro4j-gradle-plugin:1.8.0.Beta3'
classpath "io.spring.gradle:dependency-management-plugin:0.5.6.RELEASE"
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
apply plugin: 'wro4j'
apply plugin: "io.spring.dependency-management"
apply plugin: 'war'
dependencyManagement {
imports {
mavenBom 'org.springframework.cloud:spring-cloud-netflix:1.1.0.RELEASE'
}
}
jar {
baseName = 'online_store'
version = '0.1.0'
}
war {
baseName = 'online_store'
version = '0.1.0'
}
repositories {
mavenCentral()
maven { url 'http://dl.bintray.com/sbuettner/maven' }
maven { url "http://repo.spring.io/libs-snapshot" }
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
ext {
versionJQuery = '2.1.1'
versionBootstrap = '3.2.0'
versionAngular = '1.3.8'
}
springBoot {
mainClass = "com.grupomedicus.store.server.UiApplication"
executable = true
requiresUnpack = [ "org.webjars:less", "org.webjars:jshint", "org.webjars:emberjs",
"org.webjars:handlebars", "org.webjars:coffee-script", "org.webjars:jslint", "org.webjars:json2",
"org.webjars:jquery", "org.webjars:handlebars", "org.slf4j:slf4j-api"
]
}
bootRepackage {
mainClass = "com.grupomedicus.store.server.UiApplication"
}
bootRun {
addResources = true
}
configurations {
providedRuntime
}
webResources {
bundle ('core') {
js 'js/**/*.js'
preProcessor 'jsMin'
}
bundle ('angular-bootstrap') {
js "webjars/jquery/$versionJQuery/jquery.min.js"
js "webjars/angularjs/$versionAngular/angular.min.js"
js "webjars/angularjs/$versionAngular/angular-route.min.js"
}
bundle ('angular-bootstrap') {
css "webjars/bootstrap/$versionBootstrap/css/bootstrap.min.css"
css 'themes/default/main.css'
cssRewriteUrl()
}
assets {
include 'themes/default/images/**'
}
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-security')
compile("org.springframework.boot:spring-boot-starter-web")
providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("org.springframework.security:spring-security-core")
compile 'org.apache.commons:commons-lang3'
compile(group: 'de.infinit', name: 'spring-boot-autoconfigure-wro4j', version: '0.0.6')
compile "org.springframework.boot:spring-boot-starter-redis"
compile "org.springframework.session:spring-session"
compile "org.springframework.cloud:spring-cloud-starter-zuul"
webjars "org.webjars:jquery:$versionJQuery"
webjars "org.webjars:angularjs:$versionAngular"
webjars "org.webjars:bootstrap:$versionBootstrap"
testCompile("org.springframework.boot:spring-boot-starter-test")
testCompile("junit:junit")
runtime('mysql:mysql-connector-java:5.1.6')
}
task wrapper(type: Wrapper) {
gradleVersion = '2.13'
}

Unable to inject properties into a class in Spring boot sub module added as a jar in the war

I have a spring boot project with multiple modules which have to be deployed separately. Want to utilize common modules like model,dao and utilities between the projects.
When I had a single project, I was able to get the mongodb related properties loaded for MongoDBConfiguration class.
But when I have dao as a separate module, on server startup spring complains that it cannot resolve the properties required by MongoDBConfiguration class.
Here is my proj structure:
ExampleProj
dao
common
model
webmodule_x
module_y
module_z
build.gradle
Apart from main build.gradle, i have build.gradle for each module.
My dao module has MongoDBConfiguration class like this:
#Configuration
#PropertySource(value = "classpath:/application.properties")
#EnableMongoRepositories(basePackages="com.abc.xyz.dao.repositories*" )
public class MongoDBConfiguration {
#Value( "${mongo.host:abc12345.abc.com}" ) private String mongoHost;
#Value( "${mongodb.name}" ) private String mongodbName;
....
}
Tried different configurations but have the same problem.
My webmodule_x has spring boot starter class like this:
#PropertySource(value={"classpath:application.properties",
"file:${externalDirectory}/webmodule_x/conf/application.properties"
} ,
ignoreResourceNotFound = false)
#ComponentScan("com.abc.xyz")
#Configuration
#EnableAutoConfiguration
#EnableMongoRepositories(basePackages="com.abc.xyz.dao*" )
#Import(MongoDBConfiguration.class)
public class SpringBootStarter {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(SpringBootStarter.class, args);
}
}
Somehow ${mongodb.name} property is not getting initialized.
This is the error I get:
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'mongodb.name' in string value "${mongodb.name}"
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174) ~[spring-core-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126) ~[spring-core-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:204) ~[spring-core-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:178) ~[spring-core-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$2.resolveStringValue(PropertySourcesPlaceholderConfigurer.java:175) ~[spring-context-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:801) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:955) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
... 86 common frames omitted
This is my build.gradle in webmodule_x like this:
apply plugin: 'java'
apply plugin: 'spring-boot'
apply plugin: 'war'
apply plugin: 'eclipse'
apply plugin: 'idea'
def tomcat_home='/usr/local/apache-tomcat-7.0.55'
sourceCompatibility = 1.7
buildscript {
repositories {
maven { url "http://mavencentral.it.abc.com:8084/nexus/content/groups/xyz" }
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.2.5.RELEASE")
}
}
tasks.withType(org.springframework.boot.gradle.run.BootRunTask) {
systemProperties = System.properties
}
tasks.withType(Test) {
// get System properties needed for tests
systemProperties['externalDirectory'] =
System.getProperty("externalDirectory", "/opt/app/test")
println 'externalDirectory for tests is ' +
systemProperties['externalDirectory']
}
repositories {
maven { url "http://mavencentral.it.abc.com:8084/nexus/content/groups/xyz" }
}
sourceSets {
integrationTest {
java {
compileClasspath += main.output + test.output
runtimeClasspath += main.output + test.output
srcDir file('src/integration-test/java')
}
resources.srcDir file('src/integration-test/resources')
}
}
configurations{
integrationTestCompile.extendsFrom compile, testCompile
integrationTestRuntime.extendsFrom runtime, testRuntime
providedRuntime
}
dependencies {
compile 'org.springframework.boot:spring-boot-starter-web'
compile 'org.springframework:spring-webmvc')
compile project(':common')
compile project(':model')
compile project(':dao')
testCompile('junit:junit','org.hamcrest:hamcrest-library','org.mockito:mockito-core')
testCompile('junit:junit','org.hamcrest:hamcrest-library','org.springframework.boot:spring-boot-starter-test',
'org.mockito:mockito-core', 'org.skyscreamer:jsonassert:1.2.3')
integrationTestCompile('junit:junit','org.hamcrest:hamcrest-library','org.springframework.boot:spring-boot-starter-test',
'org.mockito:mockito-core', 'org.skyscreamer:jsonassert:1.2.3')
providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
}
task integrationTest(type: Test) {
description = 'Runs the integration tests.'
testClassesDir = sourceSets.integrationTest.output.classesDir
classpath = sourceSets.integrationTest.runtimeClasspath
outputs.upToDateWhen { false }
}
// logback(slf4j) commons-logging
[configurations.runtime, configurations.default]*.exclude(module: 'commons-logging')
jar.enabled = true
bootRepackage.enabled = true
My dao build.gradle:
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'eclipse'
apply plugin: 'spring-boot'
sourceCompatibility = 1.7
version = '1.0'
group = 'com.abc.xyz.dao'
version = '0.0.1-SNAPSHOT'
buildscript {
repositories {
maven { url "http://mavencentral.abc.com:8084/nexus/content/groups/xyz" }
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.2.5.RELEASE")
}
}
configurations{
providedRuntime
}
repositories {
maven { url "http://mavencentral.abc.com:8084/nexus/content/groups/xyz" }
}
dependencies {
compile 'org.springframework.data:spring-data-mongodb'
compile project(':model')
compile 'org.springframework:spring-context'
testCompile('junit:junit','org.hamcrest:hamcrest-library','org.mockito:mockito-core',
'org.mockito:mockito-core', 'org.skyscreamer:jsonassert:1.2.3', 'org.springframework.boot:spring-boot-starter-test',
'org.springframework:spring-webmvc','org.springframework.boot:spring-boot-starter-web', 'de.flapdoodle.embed:de.flapdoodle.embed.mongo:1.46.4')
providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")
}
jar.enabled = false
bootRepackage.enabled = false
Googled a lot but no luck yet. I get this error both with bootRun and with war deployment into tomcat.
Please let me know how to load properties before an injected bean in a dendent jar class is initialized.
I'm sure you have already checked this but perhaps your keys in the prop file are incorrect?
From your code, I see mongo.host and then mongodb.name
Perhaps the "db" is not in your props?

Gradle build,ojdbc6-11.2.0.3

My demo has a Maven-Dependencies ,it contains an ojdbc6.jar.
I want to build a runnable jar with Gradle.
When i run:gradle build in command line.It works well,and create a Test.jar
In build/libs folder.when i run with:java -jar Test.jar. it shows: Unable to load class: oracle.jdbc.OracleDriverclass not found.
Any one can help me out?Thanks a lot!
Caused by: java.lang.ClassNotFoundException: Unable to load class: oracle.jdbc.OracleDriver from ClassLoader:org.springframework.boot.loader.LaunchedURLClass
ssLoader:org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl$TcclSafeAggregatedClassLoader#60cbbfcd
at org.apache.tomcat.jdbc.pool.ClassLoaderUtil.loadClass(ClassLoaderUtil.java:56)
at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:268)
... 46 common frames omitted
Caused by: java.lang.ClassNotFoundException: Could not load requested class : oracle.jdbc.OracleDriver
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl$AggregatedClassLoader.findClass(ClassLoaderServiceImpl.java:230)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl$TcclSafeAggregatedClassLoader.findClass(ClassLoaderServiceImpl.java:456)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at org.apache.tomcat.jdbc.pool.ClassLoaderUtil.loadClass(ClassLoaderUtil.java:38)
I have resolved it!
Download the ojdbc7.jar in F:\
please visit oracle.com to download!
Run "cmd",then input below command:
mvn install:install-file -Dfile=f:\ojdbc7.jar -DgroupId=com.oracle.weblogic -DartifactId=ojdbc7 -
Dversion=12.1.0.2.0 -Dpackaging=jar
If setup success,you will see ojdbc7 in the bellow path:
C:\Users\Administrator.m2\repository\com\oracle\weblogic\ojdbc7\12.1.0.2.0
Here is my build.gradle:
buildscript {
repositories {
mavenCentral()
maven { url "http://repo.spring.io/libs-release" }
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-
plugin:1.2.4.RELEASE")
}
}
apply plugin: "java"
apply plugin: "eclipse"
apply plugin: "idea"
apply plugin: "spring-boot"
jar {
baseName = "Test"
version = "0.1.0"
}
repositories {
mavenCentral()
mavenLocal();
maven { url "http://repo.spring.io/libs-release" }
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("org.springframework.flex:spring-flex-core:1.6.0.RC1")
compile("com.oracle.weblogic:ojdbc7:12.1.0.2.0")
testCompile("org.springframework.boot:spring-boot-starter-test")
}
task wrapper(type: Wrapper) {
gradleVersion = "2.4"
}
tasks.withType(JavaCompile) {
options.encoding = "UTF-8"
}
The most important is add mavenLocal() to repositories

Resources