SpringBootTest failing with 'IllegalStateException - No ServletContext set' - spring

I have a pretty simple #SpringBootTest :
#RunWith(SpringRunner.class)
#SpringBootTest(classes = MyApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {...})
public class MyApplicationTest {
#Test
public void anyTest() { ... }
}
It was working as expected until we've added #EnableSchedulerLock (from Shedlock) on the MyApplication.java file.
Since, we're experiencing this issue :
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:582)
... 46 common frames omitted
Caused by: java.lang.IllegalStateException: No ServletContext set
at org.springframework.util.Assert.state(Assert.java:73)
at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.resourceHandlerMapping(WebMvcConfigurationSupport.java:483)
This happends when Spring tries to instanciate its resourceHandlerMapping :
#Bean
public HandlerMapping resourceHandlerMapping() {
Assert.state(this.applicationContext != null, "No ApplicationContext set");
Assert.state(this.servletContext != null, "No ServletContext set");
...
It's like this #Bean is created before the setServletContext (from WebMvcConfigurationSupport) is called.

As mentioned by Lukas, this error has been fixed in the latest version of Shedlock.
Upgrading Shedlock's version from 2.2.0 to 2.5.0 fixes the issue.

Related

How to correctly define hikari datasource

I have the following bean definition.
#Bean
public DataSource hikariDataSource() {
HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setJdbcUrl(JDBC_URL);
hikariConfig.setUsername(USERNAME);
hikariConfig.setPassword(PASSWORD);
return new HikariDataSource(hikariConfig);
}
When I get application context.
ApplicationContext ctx = new AnnotationConfigApplicationContext("org.example");
An exception is being thrown
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hikariDataSource' defined in org.example.config.Configuration: Failed to instantiate [javax.sql.DataSource]: Factory method 'hikariDataSource' threw exception with message: null
Is there any idea what can be the reason?
Maybe some of the answers from this thread will help.
https://stackoverflow.com/a/33213802/3816621
Also please check if you get #Configuration annotation on class level.

Spring looking for PostgreSql driver, but I'm using JTDS

Loading a spring cloud dataflow app fails with this log:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Cannot load driver class: org.postgresql.Driver
But configuration is:
spring.jpa.database=sybase
spring.datasource.url=jdbc:jtds:sybase://xxx:X000/xxxx;autoCommit=false;appName=dataflow
spring.datasource.username=xx
spring.datasource.password=xxx
spring.datasource.driver-class-name=net.sourceforge.jtds.jdbc.Driver
spring.datasource.hikari.driver-class-name=net.sourceforge.jtdatasource.jdbc.Driver
spring.datasource.hikari.pool-name=datasource-pool
spring.datasource.hikari.connection-timeout=3000
spring.datasource.hikari.maximum-pool-size=2
spring.datasource.hikari.minimum-idle=0
spring.datasource.hikari.connection-test-query=SELECT 1
spring.datasource.hikari.auto-commit=false
spring.datasource.hikari.transaction-isolation=TRANSACTION_READ_COMMITTED
Dependency:
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.3.1</version>
</dependency>
PostgreSql is never specified.
Using spring boot 2.3.3
Update:
I think something in spring dataflow context is setting the driver, because it works if I create my own configuration class and don't use spring.datasource prefix:
#Configuration
public class DataSourceConfiguration {
#Bean
#Primary
#ConfigurationProperties("spring.ds")
public DataSourceProperties dataSourceProperties() {
return new DataSourceProperties();
}
#Bean
#Primary
#ConfigurationProperties("spring.ds.hikari")
public HikariDataSource sybaseDataSource() {
return dataSourceProperties().initializeDataSourceBuilder().type(HikariDataSource.class).build();
}
}

Spring throwing Circular Reference Error with ObjectMapper and RepositoryRestMvcConfiguration

I have a Spring Boot application (2.0.3) that's throwing a circular reference error involving objectMapper (faster.xml Jackson implementation, 2.9.6). It builds fine with Gradle (4.10.2), but upon deployment throws the following error:
...; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.leroyjenkins.service.common.config.CommonConfig':
Unsatisfied dependency expressed through field 'objectMappers'; nested exception is
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'objectMapper' defined in class path resource [org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.class]:
Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [com.fasterxml.jackson.databind.ObjectMapper]:
Circular reference involving containing bean 'org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration' -
consider declaring the factory method as static for independence from its containing instance. Factory method 'objectMapper' threw exception; nested exception is java.lang.NullPointerException",
"\tat org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760)",
The CommonConfig is referring to a configuration file I have:
#Configuration
#EnableHypermediaSupport(type = .
EnableHypermediaSupport.HypermediaType.HAL)
#EnableScheduling
#Order(Ordered.LOWEST_PRECEDENCE)
#CompileStatic
#Slf4j
#Slf4jPlusMetrics("mlog")
class CommonConfig {
...
#Autowired List<ObjectMapper> objectMappers
#PostConstruct
void afterPropertiesSet() {
log.info("initializing CommonConfig objectMappersSize={},contextPath={},threadPoolSize={},threadPoolQueueCapacity={},threadPoolDefaultTimeout={},appName={}",
objectMappers.size(), contextPath, threadPoolSize, threadPoolQueueCapacity, threadPoolDefaultTimeout, appName)
objectMappers.each { ObjectMapper objectMapper ->
objectMapper.enable(SerializationFeature.INDENT_OUTPUT)
objectMapper.registerModule(new ParameterNamesModule())
objectMapper.registerModule(new Jdk8Module())
objectMapper.registerModule(new JavaTimeModule())
objectMapper.registerModule(new JodaModule())
objectMapper.registerModule(new GsnModelJacksonModule())
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
}
}
...
}
We just updated to jdk11...not sure if that's relevant here.

Usage of Spring #ConfigurationProperties gives nullpointer when running tests, JHipster app

I have implemented a simple file upload routine using Spring Boot ConfigurationProperties annotation so I can load the directory from my YAML configuration file:
Service:
#Service
public class FileSystemStorageService implements StorageService {
private final Logger log = LoggerFactory.getLogger(FileSystemStorageService.class);
private final Path pictureLocation;
#Autowired
public FileSystemStorageService(StorageProperties storageProperties) {
pictureLocation = Paths.get(storageProperties.getUpload());
}
And the StorageProperties:
#Component
#ConfigurationProperties("nutrilife.meals")
public class StorageProperties {
private String upload;
public String getUpload() {
return upload;
}
public void setUpload(String upload) {
this.upload= upload;
}
}
In the yaml file I have:
nutrilife:
meals:
upload: /$full_path_to_my_upload_dir
This works perfectly in normal Spring Boot runtime but the problem starts when I try to run my integration tests, it throws the error:
java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fileSystemStorageService' defined in file [/home/mmaia/git/nutrilife/build/classes/main/com/getnutrilife/service/upload/FileSystemStorageService.class]: Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.getnutrilife.service.upload.FileSystemStorageService]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:279)
...
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.getnutrilife.service.upload.FileSystemStorageService]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154)
So basically during tests the YAML file configuration looks like it's not being properly picked up. I am new to Spring. How can I fix it?
try adding the #value annotation :
#Value("upload")
private String upload;
The above answer is valid for application.properties config.
it also works with yaml as well.
You may find your correct correct yaml config here :
24.6 Using YAML instead of Properties

MongoDB configuration in Spring Boot and Spring Data REST

I want to use MongoDB for the mongoDB with spring-boot and JPA.. I'm able to do with embedded H2 database. But I'm not sure what's going wrong using mongo-db. While running the application, I'm getting error that datasource is missing.
#EnableAutoConfiguration
#EnableJpaRepositories(basePackages = "com..........repo")
#EnableWebMvc
#Configuration
#ComponentScan
#Import({ SpringMongoConfig.class, RepositoryRestMvcConfiguration.class })
public class Bootstrap extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Bootstrap.class, args);
}
#Override
protected SpringApplicationBuilder configure(
SpringApplicationBuilder application) {
return application.sources(Bootstrap.class);
}
}
.
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
#Configuration
#EnableMongoRepositories(basePackages = "com.............repo")
#PropertySource(value = "classpath:mongo-config.properties")
public class SpringMongoConfig extends AbstractMongoConfiguration {
#Value("${MONGO_DB_HOST}")
private String MONGO_DB_HOST;
#Value("${MONGO_DB_PORT}")
private int MONGO_DB_PORT;
#Value("${DB}")
private String DB;
#Override
protected String getDatabaseName() {
return DB;
}
#Bean
#Override
public Mongo mongo() throws Exception {
return new MongoClient(MONGO_DB_HOST, MONGO_DB_PORT);
}
}
.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:293)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1186)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
..........................
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:509)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:290)
... 25 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:597)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1095)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:990)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
....................................
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:586)
... 39 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.
at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.getDriverClassName(DataSourceProperties.java:93)
at org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource(DataSourceAutoConfiguration.java:105)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
For starters use the framework Spring Boot will do autoconfiguration for the frameworks it detects. This includes Spring Data JPA and Spring Data Mongo. So you can remove the #Enable annotation for it.
The same for Spring MVC and Spring Data Rest.
To allow Spring Boot to configure Spring Mongo add the following properties to your application.properties
spring.data.mongodb.host= # the db host
spring.data.mongodb.port=27017 # the connection port (defaults to 27107)
or the
spring.data.mongodb.uri=mongodb://localhost/test # connection URL
More on the Spring Boot Mongo support can be found in this section of the Spring Boot Reference Guide.
When not using an embedded datasource you have to specify which driver to use for this add the following property to your application.properties. This is also documented in this section of the Spring Boot Reference Guide.
spring.datasource.driverClassName=your.driver.class
I suggest moving your Bootstrap class to a top level package and remove all not needed annotations and configuration files
#EnableAutoConfiguration
#Configuration
#ComponentScan
public class Bootstrap extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Bootstrap.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Bootstrap.class);
}
}
Should be enough to bootstrap your whole application including jpa, mongo and web support.
For a quite complete list I suggest Appendix A of the Spring Boot Reference Guide.

Resources