QueryDSL annotation processor and gradle plugin - spring-boot

Cannot understand how to configure build.gradle for using querydsl annotation processor without any jpa/jdo/mongo. I want to use #QueryEntity annotation to generate Q classes so then I will be able to compose dynamic SQL queries using DSL support then convert query to plain text and provide it to Spring R2DBC DatabaseClient executor.
Is there a way what gradle querydsl apt plugin and querydsl annotation processor to use for generating Q classes with #QueryEntity annotations in build.gradle file?
I'm using gradle 5, Spring Data R2DBC, Spring Boot, plan to integrate queryDsl with annotation processsor.
That's my currect build.gradle:
plugins {
id 'java'
id 'org.springframework.boot' version '2.2.1.RELEASE'
id "com.ewerk.gradle.plugins.querydsl" version "1.0.8"
}
apply plugin: 'io.spring.dependency-management'
group = 'com.whatever'
repositories {
mavenCentral()
maven { url "https://repo.spring.io/milestone" }
}
ext {
springR2dbcVersion = '1.0.0.RELEASE'
queryDslVersion = '4.2.2'
}
dependencies {
implementation("com.querydsl:querydsl-sql:${queryDslVersion}")
implementation("com.querydsl:querydsl-apt:${queryDslVersion}")
implementation('org.springframework.boot:spring-boot-starter-webflux')
compileOnly('org.projectlombok:lombok')
annotationProcessor('org.projectlombok:lombok')
annotationProcessor('org.springframework.boot:spring-boot-configuration-processor')
annotationProcessor("com.querydsl:querydsl-apt:${queryDslVersion}")
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
testImplementation('io.projectreactor:reactor-test')
}
test {
useJUnitPlatform()
}

Generally speaking, you shouldn't use the QueryDSL plugin.
In order to configure QueryDSL generation you just need the relevant querydsl module, the annotation processors and the generated source dir. For instance, with lombok integration, this configuration should work (you might need to play with the exact QueryDSL modules you need):
buildscript {
ext {
springBootVersion = '${springBootVersion}'
queryDslVersion = '4.2.2'
javaxVersion = '1.3.2'
}
}
plugins {
id 'idea'
}
idea {
module {
sourceDirs += file('generated/')
generatedSourceDirs += file('generated/')
}
}
dependencies {
// QueryDSL
compile "com.querydsl:querydsl-sql:${queryDslVersion}"
annotationProcessor("com.querydsl:querydsl-apt:${queryDslVersion}:general")
// Lombok
compileOnly "org.projectlombok:lombok:${lombokVersion}"
annotationProcessor "org.projectlombok:lombok:${lombokVersion}"
implementation("org.projectlombok:lombok:${lombokVersion}")
// Possibly annotation processors for additional Data annotations
annotationProcessor("javax.annotation:javax.annotation-api:${javaxVersion}")
/* TEST */
// Querydsl
testCompile "com.querydsl:querydsl-sql:${queryDslVersion}"
testAnnotationProcessor("com.querydsl:querydsl-apt:${queryDslVersion}:general")
// Lombok
testImplementation("org.projectlombok:lombok:${lombokVersion}")
testAnnotationProcessor("org.projectlombok:lombok:${lombokVersion}")
testCompileOnly("org.projectlombok:lombok:${lombokVersion}")
}
Additional information: https://github.com/querydsl/querydsl/issues/2444#issuecomment-489538997

I want to leave this answer here as I struggled for several hours finding a solution that works for Kotlin (The question doesn't have a Java restriction as far as I can tell and there is really little information around for this). Kotlin supports annotation processing with the kapt plugin. In order to use this plugin for QueryDSL you need to 1. define the kapt plugin, and 2. specify the dependency that will do the processing, in this case com.querydsl:querydsl-apt. I used the general task for my plugin execution, but according to the documentation there are other options available (probably this can be useful for JPA, JDO, Hiberante with some extra tweaks)
plugins {
kotlin("kapt") version "1.4.10"
}
dependencies {
implementation("com.querydsl:querydsl-mongodb:4.4.0")
kapt("com.querydsl:querydsl-apt:4.4.0:general")
}
Now, whenever you run gradle build the annotation processing will trigger the DSL query class generation for your classes annotated with #QueryEntity. I hope it helps in case someone needs this for Kotlin.

This worked for me (Please follow the exact same order in the dependency)
sourceSets {
generated {
java {
srcDirs = ['build/generated/sources/annotationProcessor/java/main']
}
}
}
dependencies {
api 'com.querydsl:querydsl-jpa:4.4.0'
annotationProcessor 'org.projectlombok:lombok'
annotationProcessor('com.querydsl:querydsl-apt:4.4.0:jpa')
annotationProcessor('javax.annotation:javax.annotation-api')
}

This works!!!
ext {
queryDslVersion = '4.2.1'
}
sourceSets {
main {
java {
srcDirs = ['src/main/java', 'build/generated/sources/annotationProcessor/java/main']
}
}
}
dependencies {
compile("com.querydsl:querydsl-core:${queryDslVersion}")
compile("com.querydsl:querydsl-jpa:${queryDslVersion}")
}
dependencies {
compile "com.querydsl:querydsl-jpa:${queryDslVersion}"
compileOnly 'org.projectlombok:lombok:1.16.18'
annotationProcessor(
"com.querydsl:querydsl-apt:${queryDslVersion}:jpa",
"org.hibernate.javax.persistence:hibernate-jpa-2.1-api:1.0.2.Final",
"javax.annotation:javax.annotation-api:1.3.2",
"org.projectlombok:lombok"
)

for sinle gradle project just add next lines to the same build.gradle
for multi module gradle project add next lines to build.gradle of module where are jpa entities:
implementation("com.querydsl:querydsl-core:${queryDslVersion}")
annotationProcessor(
"com.querydsl:querydsl-apt:${queryDslVersion}:jpa",
"org.hibernate.javax.persistence:hibernate-jpa-2.1-api:1.0.2.Final",
"javax.annotation:javax.annotation-api:1.3.2")
and next line to build.gradle of module where are jpa repositories:
implementation("com.querydsl:querydsl-jpa:${queryDslVersion}")

Related

Spring boot multi project with gradle generates the same jar

I'm new to gradle and I'm having trouble generating multiple jars with spring boot.
I generate two different builds, but when I run build A or build B, both are A
My project has the following structure:
root
├── facade
├─── rest-api
└─── web-api
├── dependencies
├─── services
├─── entities
└─── ...
├── settings.gradle
└── build.gradle
My intention is to have a mono repo of micro services. The micro services I will generate are the web api and rest api modules of the facade directory. These modules have dependencies of the module called dependencies as its name indicates.
As I described before, when I run the web api module, it's like I'm running rest api, even asking for its dependencies.
My settings.gradle:
rootProject.name = "root"
include ":root:facade:rest-api"
include ":root:facade:web-api"
include ":root:dependencies:entities"
include ":root:dependencies:services"
...
And my build.gradle
buildscript {
ext.kotlin_version = '1.3.61'
ext.spring_boot_version = '2.2.2.RELEASE'
ext.jjwt_version = '0.10.6'
ext.klockVersion = "1.7.3"
ext.queryDslVersion = '4.1.4'
repositories {
jcenter()
mavenCentral()
}
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-plugin:$spring_boot_version"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlin_version"
classpath "org.jetbrains.kotlin:kotlin-noarg:$kotlin_version"
}
}
group 'org.com'
version '0.1.0'
def javaProjects() {
return subprojects.findAll { new File(it.projectDir, "src").exists() }
}
subprojects {
repositories {
jcenter()
mavenCentral()
}
configure(javaProjects()) {
apply plugin: "java"
apply plugin: "java-library"
apply plugin: "org.jetbrains.kotlin.jvm"
apply plugin: 'kotlin'
apply plugin: "kotlin-spring"
apply plugin: "kotlin-jpa"
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
implementation "io.jsonwebtoken:jjwt-api:$jjwt_version"
implementation "io.jsonwebtoken:jjwt-impl:$jjwt_version"
implementation "io.jsonwebtoken:jjwt-jackson:$jjwt_version"
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation "com.soywiz.korlibs.klock:klock-jvm:1.7.3"
implementation "org.jetbrains.kotlin:kotlin-reflect"
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-data-rest'
implementation "org.springframework.boot:spring-boot-starter-web"
implementation("org.springframework.boot:spring-boot-starter-security")
implementation "org.postgresql:postgresql:42.1.3"
implementation 'com.fasterxml.jackson.module:jackson-module-kotlin'
implementation "khttp:khttp:1.0.0"
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude module: 'junit'
exclude module: 'mockito-core'
}
testImplementation('org.junit.jupiter:junit-jupiter:5.5.2')
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
testImplementation('com.ninja-squad:springmockk:2.0.0')
}
allOpen {
annotation("javax.persistence.Entity")
annotation("javax.persistence.MappedSuperclass")
annotation("javax.persistence.Embeddable")
}
}
}
project(":root:dependencies:services") {
bootJar {
enabled = false
}
jar {
enabled = true
}
}
project(":root:dependencies:entities") {
bootJar {
enabled = false
}
jar {
enabled = true
}
}
...
I feel that I must have something wrong with the build.gradle, but I don't understand what.
I also have omitted the build.gradle files of the modules rest api and web api since I only have the dependencies and I have not considered it relevant.
I had previously worked with maven and followed this architecture. I don't know if gradle is the right thing to do, so I'm open to any advice you can give me.
Thank you for your attention.
As I mentioned in the comments, the correct way to include subprojects is to replace the path to the subproject with : i.e. if the subproject is in (from the root project) sub/project1, then the correct way to include it is:
include ':sub:project1'
Now as for your other question in the comments regarding:
Main class name has not been configured and it could not be resolved
You can simply do:
mainClassName = 'full.cannonical.name.of.MainClass'
If all the projects have a main class, then you need to do this in each project's build.gradle

Create custom plugin that defines plugins and dependencies

My organization uses the same Gradle plugins and dependencies for a lot of our projects. My custom plugin knowledge is pretty weak, but what I'd like to do is wrap these plugins and dependencies into a single, standalone plugin. I'm stuck on understanding how to separate the plugins/dependencies required for the plugin versus the ones that I want to use in the consuming project. Here's a simple example that I put together based on the gradle custom plugin docs, and some information about storing the plugin in a maven repo to allow it to automatically download dependencies:
// build.gradle from standalone plugin
plugins {
id 'java-gradle-plugin'
id 'maven-publish'
// these ones I don't need in the plugin, just in the project where I apply the plugin
id 'war'
id 'org.springframework.boot' version '2.2.4.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'org.asciidoctor.convert' version '1.5.8'
}
group = 'org.sample'
version = '1.0.0'
publishing {
repositories {
maven {
url "../maven-repo"
}
}
}
gradlePlugin {
plugins {
greeting {
id = "org.sample.greeter"
implementationClass = "org.sample.GreetingPlugin"
}
}
}
dependencies {
implementation gradleApi() // I think I need this for the imports in GreetingPlugin.java
implementation localGroovy() // I think I would need this if GreetingPlugin was written in Groovy
// these ones I don't need in the plugin, just in the project where I apply the plugin
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test' {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
testImplementation 'org.junit.jupiter:junit-jupiter-engine'
}
// this is only needed in the project where I apply the plugin
// I believe this should be in the GreetingPlugin.java file though
test {
useJUnitPlatform()
}
and the backing class...
package org.sample;
import org.gradle.api.DefaultTask;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.tasks.TaskAction;
class Greeting Plugin implements Plugin<Project> {
#Override
public void apply(Project project) {
project.getTasks().create("hello", MyTask.class);
}
public static class MyTask extends DefaultTask {
#TaskAction
public void myTask() {
System.out.println("Hello, World!");
}
}
}
In the project I'm trying to consume the plugin, I have the following files:
// settings.gradle
pluginManagement {
repositories {
maven {
url "../maven-repo"
}
gradlePluginPortal()
}
}
// build.gradle
plugins {
id 'org.sample.greeter' version '1.0.0'
}
My thinking is that using the plugin in this way, the project inherits the plugins and dependencies listed in the plugin code. I think I'm close, as when I ./gradlew publish I can see the plugin being applied, but it doesn't like that the spring-starter-web dependency doesn't have a version (I know that when I do a multi-project gradle repo, I need to include the dependencyManagement block with mavenBOM, so maybe that's the key?) I'm trying to follow the SpringBoot gradle plugin for insight, but it's a bit too complicated for me.
So, is this the correct way to create a standalone plugin that includes plugins/dependencies baked in? And why isn't the spring dependency manager applying the versioning?
EDIT: I followed the link from #Alan Hay, and instead of a custom plugin, I tried to use the 'apply from'. However, it still doesn't work. Here's files based on that approach:
// build.gradle from 'parent' build.gradle
plugins {
id 'war'
id 'org.springframework.boot' version '2.2.4.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'org.asciidoctor.convert' version '1.5.8'
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test' {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
testImplementation 'org.junit.jupiter:junit-jupiter-engine'
}
test {
useJUnitPlatform()
}
and attempting to reference from another project, it's the only line in the file:
apply from: '<path-to-above>/build.gradle'
This error I get is the following:
script '<path-to-above>/build.gradle': 15: Only Project build scripts can contain plugins {} blocks
See https://docs.gradle.org/5.5.1/userguide/plugins.html#sec:plugins_block for information on the plugins {} block
# line 15, column 1.
plugins {
^
1 error
A standalone, binary plugin is the preferred approach when you need to share the same build logic across multiple independent projects. Additionally, good plugin design separates capabilities from convention. In this case, the capabilities are provided by Gradle and some third-party plugins, but you're adding your own conventions on top in this plugin.
When you're implementing this, you essentially need to push the code down one level. Anything that would be configuration in the build.gradle needs to be in your plugin's source code. Anything that would impact the classpath of the buildscript (i.e. buildscript { } or plugins { }) belongs in the dependencies of your plugin. The plugins { } block in your plugin should only have the build plugins required the build the plugin itself.
// build.gradle from standalone plugin
// plugins {} should contain only plugins you need in the build of the plugin itself
plugins {
id 'java-gradle-plugin'
id 'maven-publish'
}
group = 'org.sample'
version = '1.0.0'
dependencies {
implementation gradleApi()
// Dependencies for plugins you will apply to the target build
implementation 'io.spring.gradle:dependency-management-plugin:1.0.9.RELEASE'
implementation 'org.asciidoctor:asciidoctor-gradle-jvm:2.4.0'
implementation 'org.springframework.boot:spring-boot-gradle-plugin:2.2.4.RELEASE'
}
gradlePlugin {
plugins {
greeting {
id = "org.sample.greeter"
implementationClass = "org.sample.GreetingPlugin"
}
}
}
publishing {
repositories {
maven {
url "../maven-repo"
}
}
}
package org.sample;
import org.gradle.api.DefaultTask;
import org.gradle.api.Plugin;
import org.gradle.api.plugins.JavaPlugin;
import org.gradle.api.Project;
import org.gradle.api.tasks.TaskAction;
import org.gradle.api.tasks.testing.Test;
class Greeting Plugin implements Plugin<Project> {
#Override
public void apply(Project project) {
// Apply plugins to the project (already on the classpath)
project.getPluginManager().apply("war");
project.getPluginManager().apply("org.springframework.boot");
project.getPluginManager().apply("io.spring.dependency-management");
project.getPluginManager().apply(" org.asciidoctor.convert");
// Dependencies that you need for the code in the project that this plugin is applied
DependencyHandler dependencies = project.getDependencies();
dependencies.add(JavaPlugin.IMPLEMENTATION_CONFIGURATION_NAME, "org.springframework.boot:spring-boot-starter-web");
dependencies.add(JavaPlugin.TEST_IMPLEMENTATION_CONFIGURATION_NAME, "org.junit.jupiter:junit-jupiter-engine");
dependencies.add(JavaPlugin.TEST_IMPLEMENTATION_CONFIGURATION_NAME, springBootStarterTest(dependencies));
projects.getTasks().withType(Test.class, test -> {
test.useJUnitPlatform();
});
}
private Dependency springBootStarterTest(DependencyHandler dependencies) {
Map<String, String> exclude = new HashMap<>();
exclude.put("group", "org.junit.vintage");
exclude.put("module", "junit-vintage-engine");
return ((ModuleDependency) dependencies.module("org.springframework.boot:spring-boot-starter-test")).exclude(exclude);
}
}
This is more verbose due to being written in Java, but it is functionally equivalent to putting this in your project's build.gradle:
plugins {
id 'war'
id 'org.springframework.boot' version '2.2.4.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'org.asciidoctor.convert' version '1.5.8'
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test' {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
testImplementation 'org.junit.jupiter:junit-jupiter-engine'
}
test {
useJUnitPlatform()
}

Spring Boot Test not working with Java 11

I'm trying to upgrade my existing Java 8 multi-project gradle application to Java 11. After fixing a few compilation issues, I ended up getting issues in test cases. When i run a test in Intellij, it throws the following error:
Error:java: Attempt to recreate a file for type {QueryDsl classes}
It is trying to generate the Querydsl classes but since those classes are already there, the test is throwing exception.
I'm using Java11, IntelliJ 2019, Gradle 5 to run the application.
These tests are working as expected in Java8.
I've no idea what is causing this error. Can anybody please help me in understanding this.
Code snippets are given below.
Root project build.gradle:
buildscript {
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:2.1.4.RELEASE)
classpath("net.ltgt.gradle:gradle-apt-plugin:0.21")
}
}
subprojects {
apply plugin: 'java'
repositories {
mavenCentral()
}
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
task allDependencies(type: DependencyReportTask) {}
jar {
baseName = "${parent.name}-${project.name}"
}
sourceSets {
main {
java {
srcDirs 'src/main/java', 'build/generated/sources/main/java', 'build/generated/sources/annotationProcessor/java/main'
}
}
}
}
Sub-project build.gradle:
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'net.ltgt.apt'
bootJar {
baseName = "test"
version = "1.0.0"
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-data-jpa: 2.1.4.RELEASE")
compile("com.querydsl:querydsl-core:4.1.3")
compile("com.querydsl:querydsl-jpa:4.1.3")
annotationProcessor(
"com.querydsl:querydsl-apt:4.1.3:jpa",
"javax.annotation:javax.annotation-api:1.3.2"
)
annotationProcessor("org.hibernate.javax.persistence:hibernate-jpa-2.1-api:1.0.2.Final")
testCompile("org.springframework.boot:spring-boot-starter-test:2.1.4.RELEASE")
testCompile("com.h2database:h2:2.1.4.RELEASE")
}
Integration test
#RunWith(SpringRunner.class)
#SpringBootTest(classes = MainClass.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ServiceImplTest {
#Autowired
private Service1Impl service;
#Test
public void getData() {
Data data = service.getData();
Assert.assertEquals(0, data.size());
}
}
I had the same issue and the problem was with the order of the dependencies in gradle. Somehow the java compiler in intellij can not work well.
Be sure you have this dependencies for QueryDSL
annotationProcessor group: 'com.querydsl', name: 'querydsl-apt', version: querydsl_version, classifier: 'jpa'
annotationProcessor group: 'org.hibernate.javax.persistence', name: 'hibernate-jpa-2.1-api', version: hibernate_jpa_version
annotationProcessor group: 'javax.annotation', name: 'javax.annotation-api', version: javax_annotation_version
Delete the out folder in your project just in case and rebuild with Ctrl+f9.
Note aside, executing build from gradle and test command worked fine. Check this out https://blog.jdriven.com/2018/10/using-querydsl-annotation-processor-with-gradle-and-intellij-idea/

Kotlin Gradle Could not find or load main class

I tried to copy the Spring Boot Kotlin sample project https://github.com/JetBrains/kotlin-examples/tree/master/tutorials/spring-boot-restful. I Added some more dependencies and when I tried to build the executable jar and run it, I got the error:
Could not find or load main class...
Gradle build script:
buildscript {
ext.kotlin_version = '1.1.3' // Required for Kotlin integration
ext.spring_boot_version = '1.5.4.RELEASE'
repositories {
jcenter()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" // Required for Kotlin integration
classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlin_version" // See https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-spring-compiler-plugin
classpath "org.springframework.boot:spring-boot-gradle-plugin:$spring_boot_version"
}
}
/*plugins {
id 'org.springframework.boot' version '2.0.0.RELEASE'
}*/
apply plugin: 'kotlin' // Required for Kotlin integration
apply plugin: "kotlin-spring" // See https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-spring-compiler-plugin
apply plugin: 'org.springframework.boot'
jar {
baseName = 'gs-rest-service'
version = '0.1.0'
from {
(configurations.runtime).collect {
it.isDirectory() ? it : zipTree(it)
}
}
manifest {
attributes 'Main-Class': 'org.jetbrains.kotlin.demo.Applicationkt'
}
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin/'
test.java.srcDirs += 'src/test/kotlin/'
}
repositories {
jcenter()
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" // Required for Kotlin integration
compile("org.springframework.boot:spring-boot-starter-web")
compile group: 'org.apache.camel', name: 'camel-quartz2', version: '2.20.2'
compile group: 'org.apache.camel', name: 'camel-http4', version: '2.20.2'
compile group: 'org.apache.camel', name: 'camel-docker', version: '2.20.2'
compile group: 'org.apache.camel', name: 'camel-aws', version: '2.20.2'
testCompile('org.springframework.boot:spring-boot-starter-test')
}
Change Applicationkt to ApplicationKt will work, and BTW you may upgrade Kotlin version to 1.3.50.
By Applicationkt I mean the one in this line:
attributes 'Main-Class': 'org.jetbrains.kotlin.demo.Applicationkt'
Kotlin compiles the Application file in two different files:
one file called Application.class with the Springboot things
another file called ApplicationKt.class with the main method
In this second file is where the main function is located at, so you have to use this name in the build.gradle file.
mainClassName = 'org.jetbrains.kotlin.demo.ApplicationKt'
Update your build.gradle to
jar {
manifest {
attributes 'Main-Class': 'org.jetbrains.kotlin.demo.ApplicationKt'
}
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
}
}
with an upper case K in ApplicationKt.
This is required because of the way Kotlin compiles to Java Bytecode. The fun main() function in Kotlin is not attached to any class, but Java always requires a class and does not support classless functions.
The Kotlin compiler has to create a Java class. Because you already defined a class Application it created one with the suffix Kt for the functions in your Kotlin file org/jetbrains/kotlin/demo/Application.kt. You have to set this class so that the JVM can find it.
BTW a Jar file is just a Zip file, you can unpack it and see for yourself if the ApplicationKt.class is there.
For me the main function needed to be outside the class body
#SpringBootApplication
#Configuration
class Application
(private val locationRepository: LocationRepository,
) : CommandLineRunner {
override fun run(vararg args: String?) {
whatever()
}
}
fun main(args: Array<String>) {
runApplication<Application>(*args)
}
Indeed, Kotlin create file ApplicationKt.class in the jar if your main class file is named Application.kt. You have to add the following lines:
apply plugin: 'kotlin'
apply plugin: 'application'
mainClassName = 'org.jetbrains.kotlin.demo.ApplicationKt'
If you use the classic jar plugin, you can do as below (which is described in previous responses):
jar {
manifest {
attributes 'Main-Class': 'org.jetbrains.kotlin.demo.ApplicationKt'
}
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
}
}
However, my preference is to use bootJar plugin which is much clear and which allow me to use layered jars for example:
bootJar {
layered() // Not useful if you don't want to use layered jars
}

Spring boot executable jar can not resolve freemarker template

I am learning web application building with spring boot and java. I've got my app working when I run it through Spring Tool Suite but after I build executable jar using bootRepackage and run it, It's not able to resolve the freemarker views.
I am not sure what's wrong. Any help would be appreciated.
Following is my application.properties related to freemarker,
spring.http.encoding.charset=UTF-8
spring.freemarker.cache=false
spring.freemarker.charset=utf-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.enabled=true
spring.freemarker.suffix=.html
spring.freemarker.template-loader-path=classpath:/templates/,classpath:/templates/web/
My jar structure,
BOOT-INF
classes
com
scss
static
templates
web
story.html
app
application.properties
log4j2.xml
META-INF
org
my controller,
#Controller
public class HomeController {
#Autowired
private AppLog appLogger;
#RequestMapping("/")
public ModelAndView Index(HttpServletRequest request) {
appLogger.log(Level.ERROR,AppLogSource.Web, "Reached Controller", null);
String testAttribute = request.getAttribute("com.demo.test").toString();
Map<String, String> vm = new HashMap<String, String>();
vm.put("testAttribute", testAttribute);
return new ModelAndView("/web/story", vm);
}
}
I verified that I am hitting the log step so I think issue is in resolving the view but I could be wrong and missing something else. So let me know if you need more info.
Thanks again!
Best,
Mrunal
edit
Gradle File,
buildscript {
ext {
springBootVersion = '1.4.1.RELEASE'
}
repositories {
mavenCentral()
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
classpath("com.moowork.gradle:gradle-node-plugin:1.2.0")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'spring-boot'
apply plugin: 'com.moowork.node'
apply plugin: 'com.moowork.grunt'
jar {
baseName = 'testDemo'
version = '0.0.1'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
mavenCentral()
}
node {
version = '6.11.3'
npmVersion = '3.10.10'
download = true
}
task gruntMinifyJs(type: GruntTask){
args=['minifyJs', '--debug']
}
task gruntMinifyCss(type: GruntTask){
args=['minifyCss', '--debug']
}
task buildFrontEnd(type: GruntTask) {
args = ['default', '--debug']
}
npmInstall.dependsOn(nodeSetup)
buildFrontEnd.dependsOn(npmInstall)
gruntMinifyCss.dependsOn(npmInstall)
gruntMinifyJs.dependsOn(npmInstall)
build.dependsOn(buildFrontEnd)
configurations {
all*.exclude group: 'ch.qos.logback', module:'logback-classic'
all*.exclude group: 'ch.qos.logback', module:'logback-core'
}
dependencies {
compile('org.springframework.boot:spring-boot-devtools')
compile('org.springframework.boot:spring-boot-starter-freemarker')
compile('org.springframework.boot:spring-boot-starter-security')
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.boot:spring-boot-starter:1.4.1.RELEASE'){
exclude group:'org.springframework.boot', module:'spring-boot-starter-logging'
}
compile('org.springframework.boot:spring-boot-starter-jdbc'){
exclude group:'org.apache.tomcat', module:'tomcat-jdbc'
}
compile('mysql:mysql-connector-java')
compile('com.zaxxer:HikariCP-java6:2.3.13')
compile('org.springframework.boot:spring-boot-starter-log4j2:1.4.1.RELEASE')
compile('com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.8.8')
compile('com.google.zxing:core:3.3.0')
compile('org.antlr:antlr4-runtime:4.5')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
edit 3,
further updates,
So I attached remote debugger and I found that spring is using ContentNegotiatingViewResolver to resolve the view as InternalResourceView but when I execute through spring tool suite it resolves properly to FreemarkerView.
I hope this helps someone to narrow down my issue. I'll see if I can get anywhere else in mean time by stepping through debugger.
Perhaps the freemarker jar file is not specified as a dependency in your spring boot application module. Unsure if you are running maven or gradle but do make sure you have the freemarker library included in your build.
See downloads # https://mvnrepository.com/artifact/org.freemarker/freemarker

Resources