I'm using code from book Pro Spring 5 https://github.com/Apress/pro-spring-5 which is multimodule project and even though I added
apply plugin: 'java'
apply plugin: 'idea'
idea {
module {
downloadJavadoc = true
downloadSources = true
}
}
to many build.gradle files also to the one with the highest hierarchy but I don't see any javadoc, for example when I want to see javadoc to annotation #SpringBootApplication, type ctrl+q and I don't see documentation but
org.springframework.boot.autoconfigure #Target({ElementType.TYPE})
#Retention(RetentionPolicy.RUNTIME)
#Documented
#Inherited
#SpringBootConfiguration
#EnableAutoConfiguration
#ComponentScan(excludeFilters = {#org.springframework.context.annotation.ComponentScan.Filter(type = org.springframework.context.annotation.FilterType.CUSTOM, classes = {org.springframework.boot.context.TypeExcludeFilter.class}),#org.springframework.context.annotation.ComponentScan.Filter(type = org.springframework.context.annotation.FilterType.CUSTOM, classes = {org.springframework.boot.autoconfigure.AutoConfigurationExcludeFilter.class})})
public interface SpringBootApplication
extends annotation.Annotation
Gradle: org.springframework.boot:spring-boot-autoconfigure:2.0.6.RELEASE
Related
I have created a new project with Spring Initializr:
Project: Gradle Project
Language: Java
Spring Boot: 2.7.4
Packaging: JAR
Java: 8
Dependencies:
Spring Boot Actuator, Spring Data JPA, Spring Web, H2 Database, PostgresSQL Driver, Spring Configuration Processor
After this I added some code to be able to interact with REST APIs (GET & POST). I was able to build, run, & test the project.
The next step was add Vaading, so I did the following:
Created a new package "views.main" package under the source section.
Added a MainView.java class with the following contents:
package io.enfuse.demo.fundemo.views.main;
import com.vaadin.flow.component.Key;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.checkbox.Checkbox;
import com.vaadin.flow.component.html.H1;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.router.Route;
#Route("")
public class MainView {
public MainView() {
VerticalLayout todosList = new VerticalLayout();
TextField taskField = new TextField();
Button addButton = new Button("Add");
addButton.addClickListener(click -> {
Checkbox checkbox = new Checkbox(taskField.getValue());
todosList.add(checkbox);
});
addButton.addClickShortcut(Key.ENTER);
add(
new H1("Vaadin Todo"),
todosList,
new HorizontalLayout(
taskField,
addButton
)
);
}
}
I also updated the build.gradle file to include Vaadin items:
plugins {
id 'org.springframework.boot' version '2.7.4'
id 'io.spring.dependency-management' version '1.0.14.RELEASE'
id 'com.vaadin' version '23.2.1'
id 'java'
}
group = 'io.enfuse.demo'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
ext {
set('vaadinVersion', "23.2.1")
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'com.vaadin:vaadin-spring-boot-starter'
runtimeOnly 'com.h2database:h2'
runtimeOnly 'org.postgresql:postgresql'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
dependencyManagement {
imports {
mavenBom "com.vaadin:vaadin-bom:${vaadinVersion}"
}
}
tasks.named('test') {
useJUnitPlatform()
}
Restart IntelliJ
At this point when I go to build I get the following error:
```
C:\Temp\fundemo_v2\fundemo\src\main\java\io\enfuse\demo\fundemo\views\main\MainView.java:24: error: cannot find symbol
add(
^
symbol: method add(H1,VerticalLayout,HorizontalLayout)
location: class MainView
```
I can look at the dependecies that show Vaadin is included:
What is missing exactly is not setup correctly?
Your MainView does not extend a Vaadin component and that's why there is no add method.
Try this:
public class MainView extends Div() {
I've moved a Java multi-project Gradle project to Kotlin.
In this project I use Mapstruct.
To create the required mapstruct implementation I configured kapt.
Now when I start the application, Spring Boot does not find the configuration property beans (#ConfigurationProperties) from our Infrastructure Lib (written in Java) while doing the autoconfiguration.
When I copy the generated class of Mapstruct and remove kapt, everything works fine.
Some background
build.gradle in the subproject, which is using Mapstruct:
apply plugin: "kotlin-kapt"
dependencies {
api project(":myproject-dto")
api project(":myproject-domain-model")
api "my.infrastructure:lib1"
api "my.infrastructure:lib2"
implementation "org.springframework.boot:spring-boot-starter-data-jpa"
implementation "org.springframework.cloud:spring-cloud-starter-sleuth"
implementation "net.javacrumbs.shedlock:shedlock-spring"
implementation "net.javacrumbs.shedlock:shedlock-provider-jdbc-template"
implementation "org.liquibase:liquibase-core"
kapt("org.mapstruct:mapstruct-processor")
}
Example of a configuration property bean (Java):
#Data
#ConfigurationProperties(prefix = "mymodule.config")
public class ExampleProperties {
private ClientProperties clientProperties = new ClientProperties();
#NotBlank
private String mode;
}
The main application class:
#EnableAsync
#EntityScan(basePackages = ["io.mypackage"])
#ComponentScan(basePackages = ["io.mypackage"])
#EnableFeignClients(basePackages = ["io.mypackage"])
#EnableJpaRepositories(basePackages = ["io.mypackage"])
#EnableConfigurationProperties(
value = [
ApplicationProperties::class
]
)
#ConfigurationPropertiesScan(
basePackages = [
"io.mypackage"
]
)
#SpringBootApplication
class MyApplication: SpringBootServletInitializer()
#Suppress("SpreadOperator")
fun main(args: Array<String>) {
runApplication<MyApplication>(*args)
}
Here I tried to add every scanner to my package structure, but it seems, that Spring is ignoring everything after I'm using kapt.
The main class is located in the subproject <projectname>-server and has dependencies on the other subprojects.
Any ideas why Spring Boot does not find any configuration property bean class from external jars (our infrastructure) with the component scan/configuration scan when I enable kapt?
I'm trying to Inject my mapper using mapstruct, but spring doesn't recognize the bean.
There is my mapper
package com.api.gestioncartera.Services.Mappers;
import org.mapstruct.Mapper;
import org.springframework.stereotype.Component;
import com.api.gestioncartera.Entities.CollectionCompany;
import com.api.gestioncartera.Services.DTO.CollectionCompanyDto;
#Mapper(componentModel = "spring")
public interface CollectionCompanyMapper {
CollectionCompanyDto collectionCompanyToCollectionCompanyDto(CollectionCompany collectionCompany);
}
There is my Service where I'm trying to inject it
#Service
#Transactional
public class CollectionCompanyServiceImp implements CollectionCompanyService{
#Autowired
private CollectionCompanyMapper companyMapper;
}
My gradle config
plugins {
id 'org.springframework.boot' version '2.5.6'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
...
dependencies {
...
implementation 'org.mapstruct:mapstruct:1.4.2.Final'
annotationProcessor 'org.mapstruct:mapstruct-processor:1.4.2.Final'
}
compileJava {
options.compilerArgs += [
'-Amapstruct.suppressGeneratorTimestamp=true',
'-Amapstruct.suppressGeneratorVersionInfoComment=true',
'-Amapstruct.verbose=true',
'-Amapstruct.defaultComponentModel=spring'
]
}
I also enable enable annotation processing in the IDE
Properties in the IDE
The error is:
Consider defining a bean of type 'com.api.gestioncartera.Services.Mappers.CollectionCompanyMapper' in your configuration.
I noticed that I don't have any plugin referencing mapstruct, can be this the problem? Image:
I'm using Spring Tool Suite 4 (Eclipse) + Gradle 6.8 + SrpingBoot 2.5.6
Please help!!
Eclipse has its problems with annotation processing.
I solved the issue with my projects using this plugin:
https://plugins.gradle.org/plugin/
Add this to the top of your gradle plugins.
plugins {
id "eclipse"
id "com.diffplug.eclipse.apt" version "3.37.1"
}
then do a gradle refresh.
If it‘s still not working, run
./gradlew eclipse eclipseJdtApt eclipseFactorypath
Hope this helps!
There doesn't seem to be a specific standard way I can find online that makes #DataJpaTest to run correctly.
Is it true that #DataJpaTest is not being used nowadays and all tests are run at the service or controller level using #SpringBootTest?
#Repository
public interface MyBeanRepository extends JpaRepository<MyBean, Long> {
}
#Configuration
#EnableJpaRepositories("com.app.repository.*")
#ComponentScan(basePackages = { "com.app.repository.*" })
public class ConfigurationRepository {
}
#Entity
public class MyBean {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
#Version
#Column(name = "version")
private Integer version;
#NotNull
#Size(min = 2)
private String name;
}
#DataJpaTest
public class MyBeanIntegrationTest {
#Autowired
MyBeanRepository myBeanRepository;
#Test
public void testMarkerMethod() {
}
#Test
public void testCount() {
Assertions.assertNotNull(myBeanRepository , "Data on demand for 'MyBean' failed to initialize correctly");
}
}
Running using the Eclipse->Run Junit shows these logs.
java.lang.IllegalStateException: Unable to find a #SpringBootConfiguration, you need to use #ContextConfiguration or #SpringBootTest(classes=...) with your test
at org.springframework.util.Assert.state(Assert.java:73)
Running using gradle test shows the error that init failed.
FAILURE: Build failed with an exception.
* What went wrong:
Test failed.
Failed tests:
Test com.app.repository.MyBeanIntegrationTest#initializationError (Task: :test)
Here is the gradle script.
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin")
}
}
plugins {
id 'org.springframework.boot' version '2.1.5.RELEASE'
id 'java'
id 'eclipse'
}
apply plugin: 'io.spring.dependency-management'
group = 'com.app'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenLocal()
jcenter()
mavenCentral()
}
test {
useJUnitPlatform()
}
dependencies {
// This dependency is exported to consumers, that is to say found on their compile classpath
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-validation'
runtimeOnly 'org.hsqldb:hsqldb'
testImplementation ('org.springframework.boot:spring-boot-starter-test') {
// exlcuding junit 4
exclude group: 'junit', module: 'junit'
}
/**
Test Dependencies Follows
**/
// junit 5 api
testCompile "org.junit.jupiter:junit-jupiter-api:5.2.0"
// For junit5 parameterised test support
testCompile "org.junit.jupiter:junit-jupiter-params:5.2.0"
// junit 5 implementation
testRuntime "org.junit.jupiter:junit-jupiter-engine:5.2.0"
// Only required to run junit5 test from IDE
testRuntime "org.junit.platform:junit-platform-launcher"
}
EDIT:
This has been solved and committed at the same repository.
https://github.com/john77eipe/spring-demo-1-test
It was a good idea to add a Github link. I can see following issues there:
1) If you can't have a main class annotated with #SpringBootApplication, you can use:
#SpringBootConfiguration
#EnableAutoConfiguration
#ComponentScan(basePackages = "com.app.repository")
public class MySampleApplication {
}
2) Change annotations over your ConfigurationRepository class to:
#EnableJpaRepositories("com.app.repository")
#ComponentScan(basePackages = { "com.app.repository" })
public class ConfigurationRepository {
That should let us proceed to the next point:
3) Your MyBeanIntegrationTest should be annotated as:
#SpringBootTest(classes = MyAppApplication.class)
public class MyBeanIntegrationTest {
4) In application.yml you have a small issue with indentation in the last line. Convert tab so spaces and it should be fine.
5) Next thing is MyBeanRepository interface. You can't use a method named findOne there. Thing is, that in interfaces marked as JpaRepository or CrudRepository and so on, methods names need to follow certain rules. If you mark that it will be a repository containing type MyBean your method name should be changed to findById, because Spring will look for a property named id in your bean. Naming it by findOne will cause test to fail with:
No property findOne found for type MyBean!
After fixing these things, your tests pass on my env.
I hope this helps!
I am getting a class cannot be final, needs to be open, despite adding the kotlin-spring plugin. The whole purpose of the plugin is to not manually add the open keyword to every class.
Please guide me on getting the Kotling-Spring plugin to work with code below.
build.gradle
buildscript {
ext.kotlin_version = "1.1.2"
repositories {
mavenCentral()
}
dependencies {
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"
}
}
apply plugin: "kotlin"
apply plugin: "kotlin-spring"
apply plugin: "kotlin-noarg"
apply plugin: "idea"
repositories {
mavenCentral()
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
compile"org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
compile "org.springframework:spring-context:4.3.8.RELEASE"
testCompile "org.springframework:spring-test:4.3.8.RELEASE"
testCompile "junit:junit:4.11"
}
AppConfig.java
#Configuration
class AppConfig {
#Bean
fun game(): Game {
return BaseballGame(redSox(),cubs())
}
#Bean
fun redSox(): Team {
return RedSox()
}
#Bean
fun cubs(): Team {
return Cubs()
}
}
Error:
Exception in thread "main" org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: #Configuration class 'AppConfig' may not be final. Remove the final modifier to continue.
Offending resource: AppConfig
REF: https://kotlinlang.org/docs/reference/using-gradle.html#plugin-and-versions
Had the same problem. Enabling annotation processing in Intellij solved the issue:
Had similar problem. Couldn't run from IDE, but gradlew.bat build bootRun worked. Solved by updating Kotlin plugin in IDEA, from 1.2.40 to 1.2.41.
I too faced Similar Issue while Running Springboot Application . Finally I learnt that Kotlin Class are final by Default . You need to add open before class Name
So , you need to change class modifier as follows :
open class AppConfig {
Reference :
http://engineering.pivotal.io/post/spring-boot-application-with-kotlin/