springboot thin jar, causing problems with injection - spring-boot

#Slf4j
#RestController
#RequestMapping("/admin/app")
public class AppSessionController {
private OnlineSessionService onlineSessionService;
#Autowired
public void setOnlineSessionService(OnlineSessionServiceImpl onlineSessionService) {
log.info("AppSessionController{}",this);
log.info("inject{}",onlineSessionService);
this.onlineSessionService = onlineSessionService;
log.info("after inject{}",this.onlineSessionService);
}
#PreAuthorize("hasAuthority('app:user:getOnlineUserList')")
#PostMapping("/getOnlineUserList")
Result<PageInfo<AuthData<?>>> getOnlineUserList(#RequestBody PageRequest pageRequest) {
log.info("AppSessionController{}, {}",this, this.ss);
log.info("this.onlineSessionService :"+this.onlineSessionService);
log.info("onlineSessionService :"+onlineSessionService);
PageInfo<AuthData<?>> pageInfo = onlineSessionService.getOnlineUserList(pageRequest.getPageNum(), pageRequest.getPageSize());
PageInfoFixUtil.fixPageInfo(pageInfo);
return Result.ok(pageInfo);
}
}
The output:
INFO main (AppSessionController.java:32) - AppSessionControllercom.apex.app.admin.controller.AppSessionController#5a438c0a
INFO main (AppSessionController.java:33) - inject com.apex.app.common.service.impl.OnlineSessionServiceImpl#14cd8dfa
INFO main (AppSessionController.java:36) - after inject com.apex.app.common.service.impl.OnlineSessionServiceImpl#14cd8dfa
INFO http-nio-8100-exec-5 (AppSessionController.java:48) - AppSessionControllercom.apex.app.admin.controller.AppSessionController#5a438c0a, null
INFO http-nio-8100-exec-5 (AppSessionController.java:49) - this.onlineSessionService :null
INFO http-nio-8100-exec-5 (AppSessionController.java:50) - onlineSessionService :null
The code with the problem is as above, why the onlineSessionService is null after the jar is thinned, and other controllers in the same level directory do not have this problem.
If I change the onlineSessionService to static then the injection can be injected.
gradle thin jar method:
// Copy the dependencies to the lib directory
task copyJar(type: Copy) {
// delete lib directory
delete "$buildDir\\libs\\lib"
from configurations.runtimeClasspath
into "$buildDir\\libs\\lib"
from configurations.compileClasspath
into "$buildDir\\libs\\lib"
}
task copyConfigFile(type: Copy) {
delete "$buildDir\\libs\\config"
from('src/main/resources')
into 'build/libs/config'
}
// copy configuration file
bootJar {
//archiveBaseName = 'application'
enabled = true
archiveVersion = '1.0.0'
// exclude all jars
excludes = ["*.jar"]
dependsOn copyJar
dependsOn copyConfigFile
manifest {
attributes "Manifest-Version": 1.0,
'Class-Path': configurations.runtimeClasspath.files.collect { "lib/$it.name" }.join(' ')
}
}

You should inject OnlineSessionService in constructor or by #Autowired as field rather than inject in method:
public AppSessionController(OnlineSessionService onlineSessionService){
this.onlineSessionService = onlineSessionService;
}
//Or like this
#Autowired
private OnlineSessionService onlineSessionService;
And I think the gradle config is wired, maybe use org.springframework.boot plugin to generate jar file is better than your tasks, please reference https://start.spring.io/ for more detail.

Related

NoSuchMethodException QueryDSL with Spring Boot & Spring Data Mongo

I am trying to implement Query DSL on my Spring Boot 2.0.4.RELEASE app that uses Spring Data Mongo 2.0.4.RELEASE & Gradle 4.10.
I am using Spring Tool Suite for running it locally.
Did the following steps which I found from multiple sources including Spring data documentation:
created gradle/querydsl.gradle which has below content to generate Q classes
apply plugin: "com.ewerk.gradle.plugins.querydsl"
sourceSets {
main {
java {
srcDir "$buildDir/generated/source/apt/main"
}
}
}
querydsl {
springDataMongo = true
querydslSourcesDir = "$buildDir/generated/source/apt/main"
}
dependencies {
compile "com.querydsl:querydsl-mongodb:4.1.4"
compileOnly "com.querydsl:querydsl-apt:4.1.4"
}
sourceSets.main.java.srcDirs = ['src/main/java']
Calling above gradle file from main build.gradle as shown below
buildscript {
ext { springBootVersion = "2.0.4.RELEASE" }
repositories { mavenCentral() }
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}"
classpath "gradle.plugin.com.ewerk.gradle.plugins:querydsl-plugin:1.0.9"
}
}
plugins {
id "java"
id "eclipse"
id "org.springframework.boot" version "2.0.4.RELEASE"
id "io.spring.dependency-management" version "1.0.6.RELEASE"
}
sourceCompatibility = 1.8
repositories { mavenCentral() }
dependencies {
...
compile("org.springframework.boot:spring-boot-starter-web:${springBootVersion}")
compile("org.springframework.boot:spring-boot-starter-data-mongodb:${springBootVersion}")
...
}
apply from: 'gradle/querydsl.gradle'
/* Added this because Eclipse was not able to find generated classes */
sourceSets.main.java.srcDirs = ['build/generated/source/apt/main','src/main/java']
compileJava.dependsOn processResources
processResources.dependsOn cleanResources
After this updated the Repository annotated interface as below. Note: I also use Fragment Repository FragmentOrderRepository for some custom queries.
public interface OrderRepository<D extends OrderDAO>
extends EntityRepository<D>, PagingAndSortingRepository<D, String>, FragmentOrderRepository<D>, QuerydslPredicateExecutor<D> {}
Then in controller created a GET mapping as shown here
#RestController
public class OrderController {
#GetMapping(value="/orders/dsl", produces = { "application/json" })
public ResponseEntity<List> getOrdersDSL(#QuerydslPredicate(root = OrderDAO.class) Predicate predicate, Pageable pageable, #RequestParam final MultiValueMap<String, String> parameters) {
return (ResponseEntity<List>) orderService.getTools().getRepository().findAll(predicate, pageable);
}
}
Then in my runner class I added EnableSpringDataWebSupport annotation
#SpringBootApplication
#EnableSpringDataWebSupport
public class SampleApp {
public static void main(String[] args) {
SpringApplication.run(SampleApp.class, args);
}
}
With this my app starts up without any errors but when I try hitting the path http://localhost:5057/orders/dsl?email=test#test.com
I get a NoSuchMethodException with message No primary or default constructor found for interface com.querydsl.core.types.Predicate.
Can anyone please help with some pointers to solve this issue?
It seems that parameters are not getting resolved to a type.
---- UPDATE 09/19/19 ----
While debugging I found that a class HandlerMethodArgumentResolverComposite which finds ArgumentResolver for given MethodParameter from a List of argumentResolvers(of type HandlerMethodArgumentResolver). This list does not contain QuerydslPredicateArgumentResolver. Hence it is not able to resolve the arguments.
This means QuerydslWebConfiguration which adds above resolver for Predicate type is not getting called, which in turn indicates that some AutoConfiguration is not happening.
Probably I am missing some annotation here.
Found the mistake I was doing, was missing EnableWebMvc annotation on my Configuration annotated class.
Details are in this documentation.

(Dependency) Spring MVC templates not found for embedded-tomcat spring-boot jar in parent project (gradle)?

I have a small spring boot app that does user management.
I want to include this UserManagement app as a dependency (gradle) in my other spring-boot apps.
I do not want to run the UserManagement app as stand-alone application (it needs to share beans with parent application).
I am using gradle and the spring-boot plugin.
I have included the UserManagement jar as a dependency in a spring-boot ExampleApp.
The UserManagement app runs an embedded-tomcat server on port 8081.
The ExampleApp runs an embedded-tomcat server on port 8080.
Everything works well, except for my UserManagement MVC UI.
When I hit the User-Management app on port 8081, my MVC templates are not found.
I can not seem to locate the MVC templates for the UserManagement app from the parent application, ExampleApp.
Is this even possible with spring-boot?
Yes. You can do this. I am not sure how you are sharing beans, but I suppose you could do that too.
SpringApplicationBuilder
Since the “UserManagement” app is a dependency, I would assume you are calling a method to run it from your parent application
For example, you are probably doing something like this:
public class UserManagementApplication {
private static UserManagementApplication instance = null;
private final SpringApplicationBuilder springApplicationBuilder;
private ConfigurableApplicationContext context;
private UserManagementApplication() {
this.springApplicationBuilder = new SpringApplicationBuilder(UserManagementApplication.class);
}
public static void start() {
synchronized (UserManagementApplication.class) {
if (instance == null) {
/*
******** If singleton instance is null ***************************************
******** Create a new UserManagementApplication ******************************
*/
instance = new UserManagementApplication();
}
if (instance.context == null
|| !instance.context.isActive()) {
/*
******** If the context is null or not active ********************************
******** Create new SpringApplication and run it ****************************
******** Store the resulting ConfigurableApplicationContext in memory ********
*/
instance.context = instance.springApplicationBuilder.run(new String[]{});
}
}
}
public static void stop() {
synchronized (UserManagementApplication.class) {
if (instance == null
|| instance.context == null
|| !instance.context.isActive()) return;
/*
******** If the context is active ********************************************
******** Close the context **************************************************
******** Set context back to null ********************************************
*/
instance.context.close();
instance.context = null;
}
}
public static ConfigurableApplicationContext getContext() {
if (instance == null) return null;
return instance.context;
}
}
UserManagement gradle.build and locations
Since you don’t need to run the “UserManagement” app as an
executable jar, you can ditch the spring-boot plugin and make your
own jar.
Since your are using tomcat you can put templates and static
resources in META and templates in WEB-INF.
Resources => src/main/resources/META-INF/resources/static/
Templates => src/main/resources/WEB-INF/templates/
For example, your gradle build could look something like this:
buildscript {
ext {
springBootVersion = '2.0.0.M7'
}
repositories {
mavenCentral()
maven { url "https://repo.spring.io/snapshot" }
maven { url "https://repo.spring.io/milestone" }
maven { url 'http://repo.spring.io/plugins-release' }
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
classpath 'io.spring.gradle:propdeps-plugin:0.0.9.RELEASE'
classpath 'org.springframework:springloaded:1.2.6.RELEASE'
}
}
ext {
springBootVersion = '2.0.0.M7'
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'groovy'
// apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'propdeps'
apply plugin: 'propdeps-idea'
group = 'com.example.userManagement'
sourceCompatibility = 1.8
repositories {
mavenCentral()
maven { url "https://repo.spring.io/snapshot" }
maven { url "https://repo.spring.io/milestone" }
}
configurations {
includeInJar
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.boot:spring-boot-starter-groovy-templates')
compile('org.codehaus.groovy:groovy')
includeInJar("org.webjars:bootstrap:4.0.0")
includeInJar("org.webjars:jquery:3.3.1")
configurations.compile.extendsFrom(configurations.includeInJar)
}
idea {
module {
inheritOutputDirs = true
}
}
jar {
from configurations.includeInJar.collect { it.isDirectory() ? it : zipTree(it) }
}
compileJava.dependsOn(processResources)
MVC config
Also, make sure your MVC config knows where the resources are.
For example, if you are extending the WebMvcConfigurerAdapter:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/static/**").addResourceLocations("classpath:META-INF/resources/static/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:META-INF/resources/webjars/");
registry.addResourceHandler("/**").addResourceLocations("classpath:META-INF/");
}
MVC templates
If you have a "my-bundle.min.js" file in src/main/resources/META-INF/resources/static/js, you can find it from your mvc template like this:
<script src="/resources/static/js/my-bundle.min.js"></script>
I hope this helps!

Spock test fails when using JPA Composite Key on Groovy/Gradle build

I developed a Spring Boot WebApplication that receives a soap request with some data and save it to database.
As I am a kind of beginner on Spring Boot and JPA, I used a commonly found configuration for JPA where the primary key is an Id managed by JPA.
#Table(
name="MyEntity",
uniqueConstraints=#UniqueConstraint(columnNames=["channel", "service"])
)
public class MyEntity {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
Long id
String channel
String service
I developed a set of Spock test about saving, searching and modifying entity and everything runs smoothly.
Specifically I have a Spring Boot application smoke test to be sure that configuration load correctly
#ContextConfiguration
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ApplicationContextSpec extends Specification {
#Autowired
WebApplicationContext context
def "should boot up without errors"() {
expect: "(web) application context exists"
context != null
}
}
As the natural key is channel and service, I tried to define a composite key
#Table(name="MyEntity")
#IdClass(MyEntityPk.class)
public class MyEntity {
#Id
String channel
#Id
String service
along with the primary key class (excerpt)
public class MyEntityPk implements Serializable {
String channel
String service
#ContextConfiguration
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ApplicationContextSpec extends Specification {
#Autowired
WebApplicationContext context
def "should boot up without errors"() {
expect: "(web) application context exists"
context != null
}
}
After this change, Spring Boot application smoke test fails with
java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
...
Caused by: org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
along with all other jpa related tests.
As a further information, I picked Spring Boot gs-accessing-data-jpa-master sample and adapter it to use gradle and spock. Then I modified to use a composite key and Spring Boot application smoke test is successful as expected.
On my Ws Web Application (uses dependency spring-boot-starter-web-services) there is something that causes failure. I would like to point out that the only changes were moving from auto generated key to composite key.
This causes failure to find EmbeddedServletContainerFactory. Do you have any suggestion on the matter ?
I am posting also che build script, quite complex so I added some comments to clarify implementation
buildscript {
ext {
springBootVersion = '1.5.2.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'groovy'
apply plugin: 'org.springframework.boot'
// I am using a mixed environment with some java generated source code
// and mainly groovy classes. This sourceSets definition forces to compile
// everything with groovy compiler so that java classes see groovy classes
sourceSets {
main {
groovy {
srcDirs = ['src/main/groovy', 'src/main/java']
}
java {
srcDirs = []
}
}
test {
groovy {
srcDirs = ['src/test/groovy','src/test/java']
}
java {
srcDirs = []
}
}
}
repositories {
mavenCentral()
}
// This task defines a jaxb task that takes xsd schema definition
// and generates java classes used when mapping soap requests
task genJaxb {
ext.sourcesDir = "${buildDir}/generated-sources/jaxb"
ext.classesDir = "${buildDir}/classes/jaxb"
ext.schema = "src/main/resources/myws.xsd"
outputs.dir classesDir
doLast() {
project.ant {
taskdef name: "xjc", classname: "com.sun.tools.xjc.XJCTask",
classpath: configurations.jaxb.asPath
mkdir(dir: sourcesDir)
mkdir(dir: classesDir)
xjc(destdir: sourcesDir, schema: schema) {
arg(value: "-wsdl")
produces(dir: sourcesDir, includes: "**/*.java")
}
javac(destdir: classesDir, source: 1.6, target: 1.6, debug: true,
debugLevel: "lines,vars,source",
classpath: configurations.jaxb.asPath) {
src(path: sourcesDir)
include(name: "**/*.java")
include(name: "*.java")
}
copy(todir: classesDir) {
fileset(dir: sourcesDir, erroronmissingdir: false) {
exclude(name: "**/*.java")
}
}
}
}
}
configurations {
jaxb
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("org.springframework.boot:spring-boot-starter-web-services")
compile('org.springframework.boot:spring-boot-starter-actuator')
compile("org.codehaus.groovy:groovy-all:2.4.7")
compile("wsdl4j:wsdl4j:1.6.1")
compile(files(genJaxb.classesDir).builtBy(genJaxb))
runtime('com.h2database:h2')
jaxb("org.glassfish.jaxb:jaxb-xjc:2.2.11")
testCompile 'org.springframework.boot:spring-boot-starter-test'
testCompile 'org.spockframework:spock-spring:1.0-groovy-2.4'
testCompile 'cglib:cglib-nodep:3.2.5'
}
jar {
baseName = 'myws'
version = '0.7.1'
excludes = ['**/application.yml']
from sourceSets.main.output
// adding jaxb generated file to be included in jar
from('build/classes/jaxb') {
include '**'
}
}
// this defines a uber-jar so that I may launch spring server
// from command line using java -jar myws-spring-boot.jar
task('execJar', type:Jar, dependsOn: 'jar') {
baseName = 'myws'
version = '0.7.1'
classifier = 'spring-boot'
from sourceSets.main.output
from('build/classes/jaxb') {
include '**'
}
}
bootRepackage {
withJarTask = tasks['execJar']
}
Eventually, all I have to do is:
gradlew build
to build the jar and run the tests and then
java -jar myws-spring-boot.jar
to launch the spring boot server
Smoke test was not working because I did not perform all required changes when moving from the "Long id" field as primary key
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
Long id
to
#Id
String channel
#Id
String service
I forgot to remove a method in the repository class that was referencing the "Long id" field. After moving to spring-spock 1.1 following Leonard Brünings' suggestion, I got a more detailed error message that pointed me to the right direction.
Error creating bean with name 'modelEntryRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property id found for type ModelEntryEntity!
So I removed the references (method declaration in repository interface) and smoke test ended successfully.
By the way, within build.gradle I had to add spock core explicitly, so instead of one line with reference to spring-spock 1.0 I had to put
testCompile 'org.spockframework:spock-core:1.1-groovy-2.4'
testCompile 'org.spockframework:spock-spring:1.1-groovy-2.4'

Gradle get dependency programatically without configuration

Is there an option to get Maven dependency in Gradle without using custom configuration for it? For example in custom plugin to just obtain dependency provided from extension? Something like
class DependencyPlugin implements Plugin<Project> {
void apply(Project project) {
project.extensions.create("deps", DepsExtension)
project.task('useDependency') {
doLast {
//use Gradle api to resolve dependency without custom configuration
project.resolve(project.deps.dependency)
}
}
}
}
class DepsExtension {
def dependency = 'custom:maven:1.0'
}
Something like this:
Configuration config = project.configurations.create('myPrivateConfig')
Dependency dep = project.dependencies.create('custom:maven:1.0') {
exclude group: 'foo', module: 'bar'
}
config.dependencies.add(dep)
Set<File> files = config.files
I do a similar thing in a gradle plugin here
References
https://docs.gradle.org/current/javadoc/org/gradle/api/artifacts/Configuration.html
https://docs.gradle.org/current/javadoc/org/gradle/api/artifacts/DependencySet.html
https://docs.gradle.org/current/javadoc/org/gradle/api/artifacts/dsl/DependencyHandler.html

How to configure a DSL style gradle plugin from a plugin extension

I have implemented a Gradle plugin using the Gradle DSL style. The plugin is adding multiple aspects such as a adding a custom task, and configuring more other tasks. Overall, the plugin is generating some metadata property file in a source folder that must be configured by a plugin extension.
apply plugin: 'artifactMetadata'
// configure the path for the metadata
artifactMetadata {
destinationDirectory = "src/main/generated/otherlocation/resources"
}
I have been able to figure out how to configure the task using the extension properties, however it's tricking me with the remaining stuff. What is a good approach to configure the source set, the clean task and the idea plugin (see the #n: TODO comments in the plugin code below)? The implementation below will always use the default value, not the one injected through the plugin extension.
class ArtifactMetadataPlugin implements Plugin<Project> {
public static final String EXTENSION_NAME = 'artifactMetadata'
public static final String TASK_NAME = 'generateArtifactMetadata'
void apply(Project project) {
createExtension(project)
project.configure (project) {
task (TASK_NAME, type: GenerateArtifactMetadata) {
group = project.group
artifact = project.name
version = project.version.toString()
}
sourceSets {
main {
// #1:TODO to get the plugin extension property current value here output.dir(project.artifactMetadata.destinationDirectory, builtBy: TASK_NAME)
resources.srcDirs += file(project.artifactMetadata.destinationDirectory)
}
}
clean {
// #2:TODO get the plugin extension property here
delete file(project.artifactMetadata.destinationDirectory)
}
if (project.plugins.hasPlugin(IdeaPlugin)) {
idea {
module {
// #3:TODO get the plugin extension property here
sourceDirs += file(project.artifactMetadata.destinationDirectory)
}
}
}
}
project.afterEvaluate {
def extension = project.extensions.findByName(EXTENSION_NAME)
project.tasks.withType(GenerateArtifactMetadata).all { task ->
task.destinationDirectory = project.file(extension.destinationDirectory)
}
}
}
private static void createExtension(Project project) {
def extension = project.extensions.create(EXTENSION_NAME, ArtifactMetadataPluginExtension)
extension.with {
destinationDirectory = "src/main/generated/artifactinfo/resources"
}
}
}

Resources