Creating a simple spring boot project using kotlin+Gradle and I get the following error from AWS
ATEST]7eaf7391bd074416bb2acc17a521a803, AWS_LAMBDA_INITIALIZATION_TYPE=on-demand, AWS_XRAY_DAEMON_ADDRESS=169.254.79.2:2000, _AWS_XRAY_DAEMON_PORT=2000, AWS_XRAY_CONTEXT_MISSING=LOG_ERROR, AWS_LAMBDA_FUNCTION_VERSION=$LATEST, AWS_ACCESS_KEY=ASIAU7C4QO4VEP4KLVH2, AWS_LAMBDA_FUNCTION_NAME=swaves-beach-rate}
00:14:04.221 [main] INFO org.springframework.cloud.function.adapter.aws.CustomRuntimeInitializer - AWS Handler: org.springframework.cloud.function.adapter.aws.SpringBootStreamHandler
00:14:04.321 [main] INFO lambdainternal.AWSLambda - Starting AWSLambda using Java 11.0.11 on 169.254.24.133 with PID 8 (/var/runtime/lib/aws-lambda-java-runtime-0.2.0.jar started by sbx_user1051 in /var/task)
00:14:04.321 [main] DEBUG lambdainternal.AWSLambda - Running with Spring Boot, Spring
00:14:04.321 [main] INFO lambdainternal.AWSLambda - No active profile set, falling back to default profiles: default
00:14:04.323 [main] DEBUG org.springframework.boot.SpringApplication - Loading source class com.aio.swaves.SwavesApplication
00:14:04.767 [main] DEBUG org.springframework.context.support.GenericApplicationContext - Refreshing org.springframework.context.support.GenericApplicationContext#204f30ec
00:14:04.807 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
00:14:07.024 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
00:14:07.028 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
00:14:07.039 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
00:14:07.059 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
00:14:07.083 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'swavesApplication'
00:14:07.099 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'greet'
00:14:07.139 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.boot.autoconfigure.AutoConfigurationPackages'
00:14:07.140 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.cloud.function.adapter.aws.CustomRuntimeEventLoop'
00:14:07.205 [main] INFO lambdainternal.AWSLambda - Started AWSLambda in 3.652 seconds (JVM running for 4.394)
00:14:08.210 [main] DEBUG reactor.util.Loggers - Using Slf4j logging framework
No function defined: java.lang.IllegalStateException
java.lang.IllegalStateException: No function defined
at org.springframework.cloud.function.context.AbstractSpringFunctionAdapterInitializer.apply(AbstractSpringFunctionAdapterInitializer.java:189)
at org.springframework.cloud.function.adapter.aws.SpringBootStreamHandler.handleRequest(SpringBootStreamHandler.java:55)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
END RequestId: 7ea16b3f-47d5-4763-b9fe-f97d940cf55c
REPORT RequestId: 7ea16b3f-47d5-4763-b9fe-f97d940cf55c Duration: 5006.33 ms Billed Duration: 5007 ms Memory Size: 1024 MB Max Memory Used: 166 MB Init Duration: 546.69 ms
build.gradle.kts
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import com.github.jengelman.gradle.plugins.shadow.transformers.*
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
plugins {
id("org.springframework.boot") version "2.5.4"
id("io.spring.dependency-management") version "1.0.11.RELEASE"
id("com.github.johnrengelman.shadow") version "7.0.0"
kotlin("jvm") version "1.5.21"
kotlin("plugin.spring") version "1.5.21"
}
group = "com.aio"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_11
repositories {
mavenCentral()
}
val springCloudVersion = "2020.0.3"
val awsLambdaEventsVersion = "3.10.0"
val awsLambdaCoreVersion = "1.2.1"
dependencies {
implementation("org.springframework.boot:spring-boot-starter-webflux")
implementation("org.springframework.cloud:spring-cloud-function-web")
implementation("org.springframework.cloud:spring-cloud-function-adapter-aws")
implementation("org.jsoup:jsoup:1.14.2")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
runtimeOnly("com.amazonaws:aws-lambda-java-core:${awsLambdaCoreVersion}")
runtimeOnly("com.amazonaws:aws-lambda-java-events:${awsLambdaEventsVersion}")
testImplementation("org.springframework.boot:spring-boot-starter-test") {
exclude(module = "junit")
exclude(module = "mockito-core")
}
testImplementation("io.projectreactor:reactor-test")
testImplementation("org.junit.jupiter:junit-jupiter-api")
testImplementation("com.ninja-squad:springmockk:3.0.1")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
}
dependencyManagement {
imports {
mavenBom("org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}")
}
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "11"
}
}
tasks.withType<Test> {
useJUnitPlatform()
}
tasks.assemble{
dependsOn("shadowJar")
}
tasks.withType<Jar> {
manifest {
attributes["Start-Class"] = "com.aio.swaves.SwavesApplication"
}
}
tasks.withType<ShadowJar> {
archiveClassifier.set("aws")
archiveFileName.set("swaves.jar")
dependencies {
exclude(
dependency("org.springframework.cloud:spring-cloud-function-web:3.1.3"))
}
// Required for Spring
mergeServiceFiles()
append("META-INF/spring.handlers")
append ("META-INF/spring.schemas")
append("META-INF/spring.tooling")
transform(PropertiesFileTransformer::class.java) {
val paths = arrayOf("META-INF/spring.factories")
val mergeStrategy = "append"
}
}
application.yml
spring:
cloud:
function:
definition: greet
profiles:
active: production
SwavesApplication.kt
package com.aio.swaves
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Bean
#SpringBootApplication
class SwavesApplication {
#Bean
fun greet(): (String) -> String {
return { "Hello Kotlin" }
}
}
fun main(args: Array<String>) {
runApplication<SwavesApplication>(*args)
}
Notes
Notice that the error says that there is not active profile, so it will select the default, despite that the application.yml is setting an active profile to production.
Also notice that the Bean greet is created, which means that the start-class attribute is correctly configured. I am a bit lost in what is missed, I have make it work using java but not Kotlin any suggestion?
Thanks to Oleg Zhurakousky's answer, I took my time to create samples project and document it at github. In the samples, you will find even how I push the code to AWS Lambda.
The error is that I was using the deprecated SpringBootStreamHandler instead the new FunctionInvoker.
Try to setup Flyway v6.0.8 with Spring Boot v2.2.1.RELEASE in application.yaml file:
spring:
# CockroachDB connection
r2dbc:
url: r2dbc:postgresql://localhost:26257/defaultdb
username: test_user
password: qwerty
schema: some_schema
flyway:
# Doesn't support r2dbc driver, and don't think it's really necessary just for database structuring(will be no actual data migrations)
url: jdbc:postgresql://localhost:26257/defaultdb
# schemas: some_schema
user: test_user
password: qwerty
I want to configure Flyway just using spring.flyway.url/user/password without defining any spring.datasource in addition. As I understand that's possible to do based on this merged PR but I still have faced with the following exception regarding not defined datasource:
Caused by: Error creating bean with name 'flyway' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Unsatisfied dependency expressed through method 'flyway' parameter 1; nested exception org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'spring.datasource-org.springframework.boot.autoconfigure.jdbc.DataSourceProperties': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.autoconfigure.jdbc.DataSourceProperties]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseType
What I do wrong?
build.gradle
plugins {
id 'org.flywaydb.flyway' version '6.1.1'
id 'org.springframework.boot' version '2.2.1.RELEASE'
}
apply plugin: 'io.spring.dependency-management'
repositories {
mavenCentral()
maven { url = uri("https://repo.spring.io/milestone") }
}
ext {
r2dbcPostgresqlVersion = '0.8.0.RELEASE'
postgresqlVersion = '42.2.9'
}
dependencies {
implementation("org.springframework.boot.experimental:spring-boot-starter-data-r2dbc")
implementation('org.springframework.boot:spring-boot-starter-webflux')
implementation('org.flywaydb:flyway-core')
implementation("io.r2dbc:r2dbc-postgresql:${r2dbcPostgresqlVersion}")
implementation("org.postgresql:postgresql:${postgresqlVersion}")
compileOnly('org.projectlombok:lombok')
annotationProcessor('org.projectlombok:lombok')
annotationProcessor('org.springframework.boot:spring-boot-configuration-processor')
testImplementation('org.springframework.boot:spring-boot-starter-test')
testImplementation('io.projectreactor:reactor-test')
}
dependencyManagement {
imports {
mavenBom("org.springframework.boot.experimental:spring-boot-bom-r2dbc:0.1.0.M3")
}
}
I have a configmap created in my AKS with these properties
config-application-dev.properties: |
server.port=5001
server.compression.enabled=true
azure.keyvault.uri=<URL>
azure.keyvault.client-id=<CLIENTID>
azure.keyvault.client-key=<CLIENTKEY>
My Spring boot application read those properties using #PropertySource
#PropertySource({ "${propertiesDir}/${envTarget}/config/config-application-${envTarget}.properties" })
public class Application{
...
}
And I want to read the Key using #Value property
#Value("${azure-key-vault-secret}")
private String mySecretProperty;
But, when SpringBoot starts, It throws this error message ...
It can't resolve the placeholder ...
the connection to azure is not working ?
2019-08-21 16:17:26.051 WARN 1 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'exampleController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'secret-in-keyvault' in value "${secret-in-keyvault}"
I have some multi-environment configurations.
The application.yml is like
spring:
profiles:
active: #profileActive#
The application-dev.yml is like
server:
port: 8085
spring:
application:
name: xxxx-info
datasource:
name: xxx-db
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://192.168.1.14:3306/xxx
username: root
password: *******
driver-class-name: com.mysql.jdbc.Driver
minIdle: 1
maxActive: 8
initialSize : 1
testWhileIdle: true
mybatis:
typeAliasesPackage: com.xxx.commons.common.entity
mapperLocations: classpath:mybatis/*.xml
And the application-test.yml is the same as application-dev.yml.
Application.java is like
#EnableDiscoveryClient
#SpringBootApplication
#EnableEurekaClient
#EnableFeignClients
#MapperScan("com.xxx.ggg.client.dao")
public class ClientInfoApplication {
private static final Logger LOGGER = LoggerFactory.getLogger(ClientInfoApplication.class);
public static void main(String[] args) {
SpringApplication.run(ClientInfoApplication.class, args);
}
}
Then I run spring boot application in IntelliJ
Here is the problem. Running spring boot application with application-test.yml is successful but not with application-dev.yml.
The logs are like
2018-12-17 14:27:23.497 [main][INFO]com.xxx.ggg.client.ClientInfoApplication[597]: The following profiles are active: dev
2018-12-17 14:27:24.490 [main][INFO]org.apache.coyote.http11.Http11NioProtocol[180]: Initializing ProtocolHandler ["http-nio-8080"]
2018-12-17 14:27:24.499 [main][INFO]org.apache.catalina.core.StandardService[180]: Starting service [Tomcat]
2018-12-17 14:27:24.500 [main][INFO]org.apache.catalina.core.StandardEngine[180]: Starting Servlet Engine: Apache Tomcat/8.5.31
2018-12-17 14:27:24.644 [localhost-startStop-1][INFO]org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/][180]: Initializing Spring embedded WebApplicationContext
2018-12-17 14:27:24.956 [main][WARN]org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext[551]: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clientInfoRunner': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tagService': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'tagInfoDao' defined in file [D:\projects\ggg\client-info\target\classes\com\xxx\ggg\client\dao\TagInfoDao.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sqlSessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (the profiles "dev" are currently active).
2018-12-17 14:27:24.956 [main][INFO]org.apache.catalina.core.StandardService[180]: Stopping service [Tomcat]
2018-12-17 14:27:24.981 [main][ERROR]org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter[42]:
***************************
APPLICATION FAILED TO START
***************************
Description:
Cannot determine embedded database driver class for database type NONE
Action:
If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (the profiles "dev" are currently active).
I am trying to write a standalone executable jar (fat jar) . I am using spring boot gradle plugin and writing a SpringBoot App to do this.
Here is my Application.java file
#Configuration
#EnableAutoConfiguration
#EnableRabbit
#EntityScan("persistence.domain")
#EnableJpaRepositories("persistence.repository")
#ComponentScan(basePackages = {"common","service"})
public class Application {
public static void main(final String[] args) {
final SpringApplicationBuilder appBuilder = new SpringApplicationBuilder(
Application.class);
appBuilder.profiles("common", "common_db").run(args);
}
#Bean
#Primary
#ConfigurationProperties(prefix = "spring.datasource")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
}
I have specified properties in yml files. For ex application-common etc . While running Application.java I am getting error :
[2015-09-24 14:40:22.304] boot - 32791 INFO [main] ---AnnotationConfigEmbeddedWebApplicationContext: Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#51a282af: startup date [Thu Sep 24 14:40:22 IST 2015]; root of context hierarchy
[2015-09-24 14:40:23.194] boot - 32791 WARN [main] --- AnnotationConfigEmbeddedWebApplicationContext: Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to load bean class: ; nested exception is java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration
at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:392)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:165)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:305)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:254)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:94)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:611)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:109)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:142)
at storm.Application.main(Application.java:28)
Caused by: java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration
at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:58)
at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:92)
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:190)
at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:435)
at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:389)
... 12 more
Caused by: java.lang.NullPointerException
at org.springframework.boot.autoconfigure.condition.OnPropertyCondition.getMatchOutcome(OnPropertyCondition.java:61)
at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:45)
... 16 more
Here is my build.gradle
def projects= [
":common",
":persistence",
":adapter"
]
buildscript {
repositories {
mavenCentral()
maven { url 'http://repo.spring.io/snapshot' }
maven { url 'http://repo.spring.io/milestone' }
}
dependencies { classpath group: 'org.springframework.boot', name: 'spring-boot-gradle-plugin', version: springBootVersion }
}
apply plugin: 'spring-boot'
apply plugin: 'maven-publish'
apply from: "${rootDir}/deployTasks.gradle"
springBoot {
mainClass = "storm.Application"
}
dependencies {
compile project(':common')
compile project(':adapter')
compile project(':persistence')
compile group: 'org.springframework.boot', name: 'spring-boot-starter-actuator', version: '1.1.8.RELEASE'
compile group : 'org.springframework.boot',name: 'spring-boot-autoconfigure', version : '1.1.8.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '1.1.8.RELEASE'
}
Database specification as in application-common_db.yml
database:
host: localhost
port: 3306
schema: subscriptions
username: root
password: root
autoconnect:
maxReconnects: 3
initialTimeout: 2
timeout:
connectTimeout: 0
socketTimeout: 0
failover:
host: localhost
port: 3306
queriesBeforeRetryMaster: 50
secondsBeforeRetryMaster: 30
spring:
datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://${database.host}:${database.port},${database.failover.host}:${database.failover.port}/${database.schema}?${database.properties}
username: ${database.username}
password: ${database.password}
continueOnError: true
initialize: false
initialSize: 0
timeBetweenEvictionRunsMillis: 5000
minEvictableIdleTimeMillis: 5000
removeAbandonedTimeout: 60
removeAbandoned: true
minIdle: 0
I am not sure how to resolve this error . Can nybody suggest what is going wrong here and why am i getting nullPointerException.
Help is appreciated .
Thanks
This is caused by non-matching Spring Boot dependencies. Check your classpath to find the offending resources. You have explicitly included version 1.1.8.RELEASE, but you have also included 3 other projects. Those likely contain different Spring Boot versions, leading to this error.
I know this is quite an old one, but I faced similar issue and resolved it in a different way. The actuator-autoconfigure pom somehow was invalid and so it was throwing IllegalStateException. I removed the actuator* dependencies from my maven repo and did a Maven update in eclipse, which then downloaded the correct/valid dependencies and resolved my issue.
In my case I had created a SB app from the SB Initializer and had included a fair number of deps in it to other things. I went in and commented out the refs to them in the build.gradle file and so was left with:
implementation 'org.springframework.boot:spring-boot-starter-hateoas'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'org.hsqldb:hsqldb'
runtimeOnly 'org.postgresql:postgresql'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc'
as deps. Then my bare-bones SB app was able to build and get running successfully. As I go to try to do things that may need those commented-out libs I will add them back and see what breaks.
This error is because of multiple projects having the offending resources.
Try out adding the dependencies projects another way around. (like in pom.xml or external dependencies)
I had the same its because of hibernate-core version issue when you remove the version so it resolve the problem you should try it.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.4.Final</version>
</dependency>
If it's a new project, make sure you remembered to add spring starter web dependency
I had the same its because of version incompatibility check for version or remove version if using spring boot