Spring Bean Not loaded and injected in JAAS - spring

I am trying to load the Spring UserRepository to my LoginModule but container is not loading it. To me it seems LoginContext is loading the LoginModule by dynamic loading using the config file provided to LoginContext. As this is loaded by JVM seems container is therefore ignoring LoginModule although I have tried #Component, #Service, #Configurable annotations, kindly help.
JUnit Test
#RunWith(SpringRunner.class)
#SpringBootTest
#Transactional
#ComponentScan("com.kashtech.jaas")
public class JaasLoginModuleTests {
...
#Before
public void initialize() {
System.setProperty("java.security.auth.login.config", "ebay-manager-jaas.config");
try {
lc = new LoginContext("EbayManagerLoginModule", new JaasCallBackHandler("test", "test"));
} catch (LoginException e) {
e.printStackTrace();
}
}
#Test
public void testLogin() {
try {
lc.login();
} catch (LoginException le) {
log.error("Error whilst testing login : " + le.getMessage());
}
}
LoginModule
import com.kashtech.jaas.repository.mongodb.UserRepository;
public class JaasLoginModule implements LoginModule {
#Inject
private UserRepository userRepository;
....
//find user from DB
dbUser = findUserFromDB(username);
public User findUserFromDB(String username) {
User u = userRepository.findByUsername(username);
return u;
}
}
ApplicationConfiguration
#SpringBootApplication
#ComponentScan("com.kashtech.jaas")
#EnableMongoRepositories(basePackages = "com.kashtech.jaas.repository.mongodb")
public class JaasSystemApplication {
public static void main(String[] args) {
SpringApplication.run(JaasSystemApplication.class, args);
}
}
Repository
import org.springframework.data.mongodb.repository.MongoRepository;
import com.kashtech.jaas.domain.User;
public interface UserRepository extends MongoRepository<User, String>{
public User findByUsername(String username);
}
DataSourceConfig
#Configuration
#EnableJpaRepositories("com.kashtech.jaas.repository")
#EnableTransactionManagement
public class DatasourceConfig implements EnvironmentAware {
private RelaxedPropertyResolver mongoDBResolver;
#Bean
public Mongo mongo() throws Exception {
return new MongoClient(mongoDBResolver.getProperty("host", mongoDBResolver.getProperty("port")));
}
#Bean
public MongoTemplate mongoTemplate() throws Exception {
try {
log.info("##################### Configuring Mongo DataSource ####################");
log.info("Host : " + mongoDBResolver.getProperty("host"));
log.info("Port : " + mongoDBResolver.getProperty("port"));
log.info("Database : " + mongoDBResolver.getProperty("database"));
log.info("#######################################################################");
} catch (Exception e) {
log.error("Database Connection Error ... Check the configurations.");
}
return new MongoTemplate(mongo(), mongoDBResolver.getProperty("database"));
}
Stacktrace
2017-04-28 19:19:56.551 INFO 7592 --- [ main] com.kashtech.JaasLoginModuleTests : Starting JaasLoginModuleTests on Panther with PID 7592 (started by kashif in C:\Development\workspaces\jaas-system)
2017-04-28 19:19:56.551 INFO 7592 --- [ main] com.kashtech.JaasLoginModuleTests : The following profiles are active: Dev
2017-04-28 19:19:56.578 INFO 7592 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#1757cd72: startup date [Fri Apr 28 19:19:56 BST 2017]; root of context hierarchy
2017-04-28 19:19:56.905 INFO 7592 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2017-04-28 19:19:56.924 INFO 7592 --- [ main] .RepositoryConfigurationExtensionSupport : Spring Data JPA - Could not safely identify store assignment for repository candidate interface com.kashtech.jaas.repository.mongodb.UserRepository.
2017-04-28 19:19:56.931 INFO 7592 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2017-04-28 19:19:56.982 INFO 7592 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'mongo' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=datasourceConfig; factoryMethodName=mongo; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/kashtech/jaas/config/DatasourceConfig.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; factoryMethodName=mongo; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/mongo/MongoAutoConfiguration.class]]
2017-04-28 19:19:57.190 INFO 7592 --- [ main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2017-04-28 19:19:57.359 INFO 7592 --- [ main] c.kashtech.jaas.config.DatasourceConfig : ##################### Configuring DataSource #####################
2017-04-28 19:19:57.359 INFO 7592 --- [ main] c.kashtech.jaas.config.DatasourceConfig : Driver class : com.mysql.jdbc.Driver
2017-04-28 19:19:57.359 INFO 7592 --- [ main] c.kashtech.jaas.config.DatasourceConfig : Driver URL : jdbc:mysql://localhost/ebay-manager
2017-04-28 19:19:57.359 INFO 7592 --- [ main] c.kashtech.jaas.config.DatasourceConfig : Driver username : root
2017-04-28 19:19:57.360 INFO 7592 --- [ main] c.kashtech.jaas.config.DatasourceConfig : Driver password : admin
2017-04-28 19:19:57.480 INFO 7592 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2017-04-28 19:19:57.499 INFO 7592 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2017-04-28 19:19:57.573 INFO 7592 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.0.12.Final}
2017-04-28 19:19:57.575 INFO 7592 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2017-04-28 19:19:57.576 INFO 7592 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2017-04-28 19:19:57.618 INFO 7592 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Fri Apr 28 19:19:57 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Fri Apr 28 19:19:58 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Fri Apr 28 19:19:58 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Fri Apr 28 19:19:58 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Fri Apr 28 19:19:58 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Fri Apr 28 19:19:58 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Fri Apr 28 19:19:58 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Fri Apr 28 19:19:58 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Fri Apr 28 19:19:58 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Fri Apr 28 19:19:58 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
2017-04-28 19:19:58.159 INFO 7592 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2017-04-28 19:19:58.440 WARN 7592 --- [ main] o.h.b.i.SessionFactoryBuilderImpl : Unrecognized hbm2ddl_auto value : none. Supported values include create, create-drop, update, and validate. Ignoring
2017-04-28 19:19:58.556 INFO 7592 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2017-04-28 19:19:58.575 INFO 7592 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2017-04-28 19:19:58.575 INFO 7592 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2017-04-28 19:19:58.585 INFO 7592 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2017-04-28 19:19:58.596 WARN 7592 --- [ main] o.h.b.i.SessionFactoryBuilderImpl : Unrecognized hbm2ddl_auto value : none. Supported values include create, create-drop, update, and validate. Ignoring
2017-04-28 19:19:58.602 WARN 7592 --- [ main] o.h.j.i.EntityManagerFactoryRegistry : HHH000436: Entity manager factory name (default) is already registered. If entity manager will be clustered or passivated, specify a unique value for property 'hibernate.ejb.entitymanager_factory_name'
2017-04-28 19:19:58.602 INFO 7592 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2017-04-28 19:19:58.646 INFO 7592 --- [ main] c.kashtech.jaas.config.DatasourceConfig : ##################### Configuring Mongo DataSource ####################
2017-04-28 19:19:58.646 INFO 7592 --- [ main] c.kashtech.jaas.config.DatasourceConfig : Host : 127.0.0.1
2017-04-28 19:19:58.646 INFO 7592 --- [ main] c.kashtech.jaas.config.DatasourceConfig : Port : 27017
2017-04-28 19:19:58.646 INFO 7592 --- [ main] c.kashtech.jaas.config.DatasourceConfig : Database : ebay-manager
2017-04-28 19:19:58.646 INFO 7592 --- [ main] c.kashtech.jaas.config.DatasourceConfig : #######################################################################
2017-04-28 19:19:59.212 INFO 7592 --- [ main] org.mongodb.driver.cluster : Cluster created with settings {hosts=[127.0.0.1:27017], mode=MULTIPLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2017-04-28 19:19:59.212 INFO 7592 --- [ main] org.mongodb.driver.cluster : Adding discovered server 127.0.0.1:27017 to client view of cluster
2017-04-28 19:19:59.309 INFO 7592 --- [127.0.0.1:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:18}] to 127.0.0.1:27017
2017-04-28 19:19:59.311 INFO 7592 --- [127.0.0.1:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=127.0.0.1:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 4, 2]}, minWireVersion=0, maxWireVersion=5, maxDocumentSize=16777216, roundTripTimeNanos=613444}
2017-04-28 19:19:59.312 INFO 7592 --- [127.0.0.1:27017] org.mongodb.driver.cluster : Discovered cluster type of STANDALONE
2017-04-28 19:19:59.453 INFO 7592 --- [ main] org.mongodb.driver.connection : Opened connection [connectionId{localValue:2, serverValue:19}] to 127.0.0.1:27017
2017-04-28 19:19:59.915 INFO 7592 --- [ main] com.kashtech.JaasLoginModuleTests : Started JaasLoginModuleTests in 3.67 seconds (JVM running for 4.403)
2017-04-28 19:20:00.035 INFO 7592 --- [ main] o.s.t.c.transaction.TransactionContext : Began transaction (1) for test context [DefaultTestContext#103f852 testClass = JaasLoginModuleTests, testInstance = com.kashtech.JaasLoginModuleTests#44a3ec6b, testMethod = testLogin#JaasLoginModuleTests, testException = [null], mergedContextConfiguration = [MergedContextConfiguration#587c290d testClass = JaasLoginModuleTests, locations = '{}', classes = '{class com.kashtech.JaasSystemApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer#14acaea5, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer#59fa1d9b, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer#0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer#0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer#77cd7a0], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]]; transaction manager [org.springframework.orm.jpa.JpaTransactionManager#60c8a093]; rollback [true]
2017-04-28 19:20:00.065 INFO 7592 --- [ main] com.kashtech.JaasLoginModuleTests : Callback Handler invoked
test
2017-04-28 19:20:00.068 ERROR 7592 --- [ main] com.kashtech.JaasLoginModuleTests : Error whilst testing login : java.lang.NullPointerException
at com.kashtech.jaas.domain.JaasLoginModule.findUserFromDB(JaasLoginModule.java:307)
at com.kashtech.jaas.domain.JaasLoginModule.login(JaasLoginModule.java:146)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at javax.security.auth.login.LoginContext.invoke(Unknown Source)
at javax.security.auth.login.LoginContext.access$000(Unknown Source)
at javax.security.auth.login.LoginContext$4.run(Unknown Source)
at javax.security.auth.login.LoginContext$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.login.LoginContext.invokePriv(Unknown Source)
at javax.security.auth.login.LoginContext.login(Unknown Source)
at com.kashtech.JaasLoginModuleTests.testLogin(JaasLoginModuleTests.java:73)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
2017-04-28 19:20:00.077 INFO 7592 --- [ main] o.s.t.c.transaction.TransactionContext : Rolled back transaction for test context [DefaultTestContext#103f852 testClass = JaasLoginModuleTests, testInstance = com.kashtech.JaasLoginModuleTests#44a3ec6b, testMethod = testLogin#JaasLoginModuleTests, testException = java.lang.NullPointerException, mergedContextConfiguration = [MergedContextConfiguration#587c290d testClass = JaasLoginModuleTests, locations = '{}', classes = '{class com.kashtech.JaasSystemApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer#14acaea5, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer#59fa1d9b, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer#0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer#0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer#77cd7a0], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]].
2017-04-28 19:20:00.086 INFO 7592 --- [ Thread-3] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext#1757cd72: startup date [Fri Apr 28 19:19:56 BST 2017]; root of context hierarchy
2017-04-28 19:20:00.089 INFO 7592 --- [ Thread-3] org.mongodb.driver.connection : Closed connection [connectionId{localValue:2, serverValue:19}] to 127.0.0.1:27017 because the pool has been closed.
2017-04-28 19:20:00.091 INFO 7592 --- [ Thread-3] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'

You're calling new which init's the class outside of the IoC container and thus spring cannot inject into it. Autowire the class into the unit test. Your JaasLoginModule needs to be defined as a Bean, Component, Service and then autowired to the test class.

Related

How to create an H2+flyway test database in spring boot?

I have a spring boot project where I want to test my controller.I use MySql database for production but want an in memory database for running the testcases.I use Flyway for versioning database migration.I want my test database to use the same versioning.Can someone please help me with a way to do that?
This is what my application.properties in src/test/resources folder looks like:
# Database Properties
spring.jpa.database=H2
spring.database.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MODE=MySQL;INIT=CREATE SCHEMA IF NOT EXISTS public;DATABASE_TO_UPPER=false
spring.h2.console.enabled=true
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect
security.basic.enabled:false
spring.datasource.username:sa
spring.datasource.password:
# Flyway Properties
spring.flyway.locations=filesystem:src/main/resources/db/migration
spring.flyway.enabled=true
spring.flyway.baseline-on-migrate=true
This is my Test File:
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
#SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
#AutoConfigureMockMvc
#ContextConfiguration
public class PermissionsControllerTest {
#Autowired
private MockMvc mockMvc;
#Test
public void existentUserCanGetTokenAndAuthenticationAndAlsoExtractPermissions() throws Exception {
String username = "Srishti";
String body = "{" + "\"username\":\"" + username + "\"}";
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/authenticate")
.contentType(MediaType.APPLICATION_JSON_VALUE).content(body)).andDo(print()).andExpect(status().isOk())
.andReturn();
String response = result.getResponse().getContentAsString();
mockMvc.perform(MockMvcRequestBuilders.get("/permission").header("Authorization", "Bearer " + response))
.andExpect(status().isOk()).andDo(print()).andReturn();
mockMvc.perform(MockMvcRequestBuilders.get("/permission/9").header("Authorization", "Bearer " + response))
.andExpect(status().isOk()).andDo(print()).andReturn();
}
}
And this is the output that I get currently get:
2020-09-06 19:30:54.481 INFO 26936 --- [ main] c.t.L.PermissionsControllerTest : Starting PermissionsControllerTest on DGKDSQ13 with PID 26936 (started by SrishtiChawla in C:\Users\srishtichawla\Desktop\LCTraining\LCTraining)
2020-09-06 19:30:54.483 INFO 26936 --- [ main] c.t.L.PermissionsControllerTest : No active profile set, falling back to default profiles: default
2020-09-06 19:30:55.599 INFO 26936 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2020-09-06 19:30:55.600 INFO 26936 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JDBC repositories in DEFAULT mode.
2020-09-06 19:30:55.670 INFO 26936 --- [ main] .RepositoryConfigurationExtensionSupport : Spring Data JDBC - Could not safely identify store assignment for repository candidate interface com.training.LCtraining.repository.LOBRepository. If you want this repository to be a JDBC repository, consider annotating your entities with one of these annotations: org.springframework.data.relational.core.mapping.Table.
2020-09-06 19:30:55.672 INFO 26936 --- [ main] .RepositoryConfigurationExtensionSupport : Spring Data JDBC - Could not safely identify store assignment for repository candidate interface com.training.LCtraining.repository.PermissionsRepository. If you want this repository to be a JDBC repository, consider annotating your entities with one of these annotations: org.springframework.data.relational.core.mapping.Table.
2020-09-06 19:30:55.674 INFO 26936 --- [ main] .RepositoryConfigurationExtensionSupport : Spring Data JDBC - Could not safely identify store assignment for repository candidate interface com.training.LCtraining.repository.ProductCategoryRepository. If you want this repository to be a JDBC repository, consider annotating your entities with one of these annotations: org.springframework.data.relational.core.mapping.Table.
2020-09-06 19:30:55.677 INFO 26936 --- [ main] .RepositoryConfigurationExtensionSupport : Spring Data JDBC - Could not safely identify store assignment for repository candidate interface com.training.LCtraining.repository.RolesRepository. If you want this repository to be a JDBC repository, consider annotating your entities with one of these annotations: org.springframework.data.relational.core.mapping.Table.
2020-09-06 19:30:55.679 INFO 26936 --- [ main] .RepositoryConfigurationExtensionSupport : Spring Data JDBC - Could not safely identify store assignment for repository candidate interface com.training.LCtraining.repository.ScoringModelSuiteRepository. If you want this repository to be a JDBC repository, consider annotating your entities with one of these annotations: org.springframework.data.relational.core.mapping.Table.
2020-09-06 19:30:55.681 INFO 26936 --- [ main] .RepositoryConfigurationExtensionSupport : Spring Data JDBC - Could not safely identify store assignment for repository candidate interface com.training.LCtraining.repository.UserRepository. If you want this repository to be a JDBC repository, consider annotating your entities with one of these annotations: org.springframework.data.relational.core.mapping.Table.
2020-09-06 19:30:55.682 INFO 26936 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 74ms. Found 0 JDBC repository interfaces.
2020-09-06 19:30:55.694 INFO 26936 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2020-09-06 19:30:55.695 INFO 26936 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFERRED mode.
2020-09-06 19:30:55.762 INFO 26936 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 63ms. Found 6 JPA repository interfaces.
2020-09-06 19:30:56.308 INFO 26936 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler#1e5eb20a' of type [org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-09-06 19:30:56.325 INFO 26936 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'methodSecurityMetadataSource' of type [org.springframework.security.access.method.DelegatingMethodSecurityMetadataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-09-06 19:30:57.018 INFO 26936 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 0 (http)
2020-09-06 19:30:57.032 INFO 26936 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-09-06 19:30:57.033 INFO 26936 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.37]
2020-09-06 19:30:57.216 INFO 26936 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-09-06 19:30:57.216 INFO 26936 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2708 ms
2020-09-06 19:30:57.353 WARN 26936 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-09-06 19:30:57.509 INFO 26936 --- [ main] o.f.c.internal.license.VersionPrinter : Flyway Community Edition 6.4.4 by Redgate
2020-09-06 19:30:57.515 INFO 26936 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-09-06 19:30:57.746 INFO 26936 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-09-06 19:30:57.773 INFO 26936 --- [ main] o.f.c.internal.database.DatabaseFactory : Database: jdbc:h2:mem:testdb (H2 1.4)
2020-09-06 19:30:57.864 INFO 26936 --- [ main] o.f.core.internal.command.DbValidate : Successfully validated 9 migrations (execution time 00:00.036s)
2020-09-06 19:30:57.883 INFO 26936 --- [ main] o.f.c.i.s.JdbcTableSchemaHistory : Creating Schema History table "PUBLIC"."flyway_schema_history" ...
2020-09-06 19:30:57.955 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Current version of schema "PUBLIC": << Empty Schema >>
2020-09-06 19:30:57.970 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema "PUBLIC" to version 1.1 - createTables
2020-09-06 19:30:58.100 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema "PUBLIC" to version 1.2 - inservalues
2020-09-06 19:30:58.144 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema "PUBLIC" to version 1.3 - altertable
2020-09-06 19:30:58.183 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema "PUBLIC" to version 1.4 - INSERTVALUES2
2020-09-06 19:30:58.216 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema "PUBLIC" to version 1.5 - insertvalues3
2020-09-06 19:30:58.241 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema "PUBLIC" to version 1.6 - ALTERTABLE
2020-09-06 19:30:58.264 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema "PUBLIC" to version 1.7 - Altertablelob
2020-09-06 19:30:58.293 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema "PUBLIC" to version 1.8 - insertvals
2020-09-06 19:30:58.315 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema "PUBLIC" to version 1.10 - uniquekey
2020-09-06 19:30:58.330 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Successfully applied 9 migrations to schema "PUBLIC" (execution time 00:00.383s)
2020-09-06 19:30:58.541 INFO 26936 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-09-06 19:30:58.639 INFO 26936 --- [ task-1] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-09-06 19:30:58.711 INFO 26936 --- [ task-1] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.18.Final
2020-09-06 19:30:58.903 INFO 26936 --- [ task-1] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-09-06 19:30:59.060 INFO 26936 --- [ task-1] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2020-09-06 19:30:59.320 INFO 26936 --- [ main] o.s.b.a.h2.H2ConsoleAutoConfiguration : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:testdb'
2020-09-06 19:30:59.970 INFO 26936 --- [ task-1] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-09-06 19:30:59.982 INFO 26936 --- [ task-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-09-06 19:31:00.409 INFO 26936 --- [ main] o.s.b.a.e.web.EndpointLinksResolver : Exposing 2 endpoint(s) beneath base path '/actuator'
2020-09-06 19:31:00.489 INFO 26936 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#1c43e84e, org.springframework.security.web.context.SecurityContextPersistenceFilter#5e62ca19, org.springframework.security.web.header.HeaderWriterFilter#493968a9, org.springframework.web.filter.CorsFilter#7bd694a5, org.springframework.security.web.authentication.logout.LogoutFilter#322ab6ce, com.training.LCtraining.filter.JwtFilter#af9dd34, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#6528d339, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#3149409c, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#21ce2e4d, org.springframework.security.web.session.SessionManagementFilter#780c0, org.springframework.security.web.access.ExceptionTranslationFilter#7a8b7e11, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#11ee671f]
2020-09-06 19:31:01.178 INFO 26936 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring TestDispatcherServlet ''
2020-09-06 19:31:01.179 INFO 26936 --- [ main] o.s.t.web.servlet.TestDispatcherServlet : Initializing Servlet ''
2020-09-06 19:31:01.195 INFO 26936 --- [ main] o.s.t.web.servlet.TestDispatcherServlet : Completed initialization in 16 ms
2020-09-06 19:31:01.298 INFO 26936 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 51516 (http) with context path ''
2020-09-06 19:31:01.300 INFO 26936 --- [ main] DeferredRepositoryInitializationListener : Triggering deferred initialization of Spring Data repositories…
2020-09-06 19:31:01.785 INFO 26936 --- [ main] DeferredRepositoryInitializationListener : Spring Data repositories initialized!
2020-09-06 19:31:01.801 INFO 26936 --- [ main] c.t.L.PermissionsControllerTest : Started PermissionsControllerTest in 7.711 seconds (JVM running for 9.214)
Hibernate: select user0_.user_id as user_id1_9_, user0_.lob_id as lob_id4_9_, user0_.enabled as enabled2_9_, user0_.role_id as role_id5_9_, user0_.username as username3_9_ from user user0_ where user0_.username=?
2020-09-06 19:31:02.278 WARN 26936 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 42102, SQLState: 42S02
2020-09-06 19:31:02.279 ERROR 26936 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : Table "user" not found; SQL statement:
select user0_.user_id as user_id1_9_, user0_.lob_id as lob_id4_9_, user0_.enabled as enabled2_9_, user0_.role_id as role_id5_9_, user0_.username as username3_9_ from user user0_ where user0_.username=? [42102-200]
MockHttpServletRequest:
HTTP Method = POST
Request URI = /authenticate
Parameters = {}
Headers = [Content-Type:"application/json;charset=UTF-8", Content-Length:"22"]
Body = {"username":"Srishti"}
Session Attrs = {}
Handler:
Type = com.training.LCtraining.integration.UserRestController
Method = com.training.LCtraining.integration.UserRestController#generateToken(AuthRequest)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = org.springframework.dao.InvalidDataAccessResourceUsageException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 401
Error message = null
Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", Content-Type:"application/json", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
Content type = application/json
Body = {"timestamp":"2020-09-06","message":"could not prepare statement; SQL [select user0_.user_id as user_id1_9_, user0_.lob_id as lob_id4_9_, user0_.enabled as enabled2_9_, user0_.role_id as role_id5_9_, user0_.username as username3_9_ from user user0_ where user0_.username=?]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement","details":"uri=/authenticate"}
Forwarded URL = null
Redirected URL = null
Cookies = []
MockHttpServletRequest:
HTTP Method = POST
Request URI = /authenticate
Parameters = {}
Headers = [Content-Type:"application/json;charset=UTF-8", Content-Length:"22"]
Body = {"username":"Srishti"}
Session Attrs = {}
Handler:
Type = com.training.training.integration.UserRestController
Method = com.training.training.integration.UserRestController#generateToken(AuthRequest)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = org.springframework.dao.InvalidDataAccessResourceUsageException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 401
Error message = null
Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", Content-Type:"application/json", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
Content type = application/json
Body = {"timestamp":"2020-09-06","message":"could not prepare statement; SQL [select user0_.user_id as user_id1_9_, user0_.lob_id as lob_id4_9_, user0_.enabled as enabled2_9_, user0_.role_id as role_id5_9_, user0_.username as username3_9_ from user user0_ where user0_.username=?]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement","details":"uri=/authenticate"}
Forwarded URL = null
Redirected URL = null
Cookies = []
2020-09-06 19:31:02.656 INFO 26936 --- [extShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-09-06 19:31:02.659 INFO 26936 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2020-09-06 19:31:02.659 INFO 26936 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2020-09-06 19:31:02.664 INFO 26936 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
The controllers are working fine on the production side.
This is my V1.1__createtable.sql file
create table permissions(
permissionID int not null auto_increment,
permissionTitle varchar(40) not null,
permissionDescription varchar(255),
PRIMARY KEY (permissionID),
UNIQUE (permissionTitle));
insert into permissions(permissionTitle) values('Create Role');
insert into permissions(permissionTitle) values('Edit Role');
insert into permissions(permissionTitle) values('Delete Role');
insert into permissions(permissionTitle) values('Create User');
insert into permissions(permissionTitle) values('Edit User');
insert into permissions(permissionTitle) values('Delete User');
insert into permissions(permissionTitle) values('Create LOB');
insert into permissions(permissionTitle) values('Edit LOB');
insert into permissions(permissionTitle) values('Delete LOB');
According to the logs, Flyway is executed successfully:
Flyway Community Edition 6.4.4 by Redgate
HikariPool-1 - Starting...
HikariPool-1 - Start completed.
Database: jdbc:h2:mem:testdb (H2 1.4)
Successfully validated 9 migrations (execution time 00:00.036s)
Creating Schema History table "PUBLIC"."flyway_schema_history" ...
Current version of schema "PUBLIC": << Empty Schema >>
Migrating schema "PUBLIC" to version 1.1 - createTables
Migrating schema "PUBLIC" to version 1.2 - inservalues
Migrating schema "PUBLIC" to version 1.3 - altertable
Migrating schema "PUBLIC" to version 1.4 - INSERTVALUES2
Migrating schema "PUBLIC" to version 1.5 - insertvalues3
Migrating schema "PUBLIC" to version 1.6 - ALTERTABLE
Migrating schema "PUBLIC" to version 1.7 - Altertablelob
Migrating schema "PUBLIC" to version 1.8 - insertvals
Migrating schema "PUBLIC" to version 1.10 - uniquekey
Successfully applied 9 migrations to schema "PUBLIC" (execution time 00:00.383s)
You can see that 9 migrations are applied: createTables, inservalues, altertable, INSERTVALUES2, insertvalues3, ALTERTABLE, Altertablelob, insertvals, uniquekey.
Is this list complete or are you expecting more migrations?
The error you see later in the log comes from Hibernate, not from Flyway.
And it says:
Table "user" not found
Looking the migration names, I would expect that the user table is created by the createTables migration. But there's no CREATE TABLE 'user' statement in V1.1__createTables.sql.
Please double-check that all necessary tables are defined in your migrations. You should NOT alter old migrations. Instead, you can create new migrations for the missing tables and use CREATE TABLE IF NOT EXISTS syntax, so that it's compatible with existing production environment.
I had a similar problem and my solution was described in a comment by #Srish. Changing my url from jdbc:h2:mem:[MYDB] to jdbc:h2:file:~/[MYDB] allowed flyway to successfully perform the migrations as well perform JPA's validation.

Spring boot H2 console returns 404

I have a simple Springboot application and it's up running. I am able to call REST endpoints through Postman. However, when I try to access the console using http://localhost:8080/h2 it keeps returning 404.
2020-08-29 08:06:37.577 INFO 6507 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2020-08-29 08:06:37.644 INFO 6507 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.2.17.Final}
2020-08-29 08:06:37.645 INFO 6507 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2020-08-29 08:06:37.677 INFO 6507 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2020-08-29 08:06:37.787 INFO 6507 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2020-08-29 08:06:38.247 INFO 6507 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-08-29 08:06:38.737 INFO 6507 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2020-08-29 08:06:38.738 INFO 6507 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'dataSource' has been autodetected for JMX exposure
2020-08-29 08:06:38.741 INFO 6507 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource]
2020-08-29 08:06:38.813 INFO 6507 --- [ctor-http-nio-1] r.ipc.netty.tcp.BlockingNettyContext : Started HttpServer on /0:0:0:0:0:0:0:0:8080
2020-08-29 08:06:38.813 INFO 6507 --- [ main] o.s.b.web.embedded.netty.NettyWebServer : Netty started on port(s): 8080
2020-08-29 08:06:38.816 INFO 6507 --- [ main] c.v.t.c.m.tenant.discovery.Application : Started Application in 3.4 seconds (JVM running for 3.661)
2020-08-29 08:06:48.527 WARN 6507 --- [ctor-http-nio-2] .a.w.r.e.DefaultErrorWebExceptionHandler : Failed to handle request [GET http://localhost:8080/h2]: Response status 404
2020-08-29 08:23:07.301 WARN 6507 --- [l-1 housekeeper] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Retrograde clock change detected (housekeeper delta=29s626ms), soft-evicting connections from pool.
2020-08-29 08:57:06.586 WARN 6507 --- [l-1 housekeeper] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Thread starvation or clock leap detected (housekeeper delta=33m59s284ms).
2020-08-29 09:35:49.699 WARN 6507 --- [l-1 housekeeper] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Thread starvation or clock leap detected (housekeeper
My application.yml file looks like this.
spring:
datasource:
url: jdbc:h2:mem:test
platform: h2
username: sa
password:
driverClassName: org.h2.Driver
hikari:
maximum-pool-size: 50
h2:
console:
enabled: true
path: /h2
settings:
web-allow-others: true
jpa:
database-platform: org.hibernate.dialect.H2Dialect
hibernate:
ddl-auto: update
server:
port: 8080
As per your logs, I found that, you are using an embedded server, other than tomcat, i.e, spring-boot-starter-reactor-netty that comes along with spring webflux dependency.
H2ConsoleAutoConfiguration will not be executed for spring webflux & netty(reactor based), as H2 console will only be available to servlet based applications. So, you have to configure H2 server manually in this spring boot application, with spring webflux & netty.
Sample H2Server (working code):
package com.example.springbootnettyserver;
import org.h2.tools.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import static org.h2.tools.Server.createWebServer;
#Component
public class H2ServerManual {
Logger log = LoggerFactory.getLogger(H2ServerManual.class);
private Server webServer;
#Value("${h2-server.port}")
Integer h2ConsolePort;
#EventListener(ContextRefreshedEvent.class)
public void start() throws java.sql.SQLException {
log.info("starting h2 console at port "+ h2ConsolePort);
this.webServer = createWebServer("-webPort", h2ConsolePort.toString(),
"-tcpAllowOthers").start();
System.out.println(webServer.getURL());
}
#EventListener(ContextClosedEvent.class)
public void stop() {
log.info("stopping h2 console at port "+h2ConsolePort);
this.webServer.stop();
}
}
Note: org.h2.tools.Server class will be resolved only when h2 dependency is added without scope of runtime. (remove scope element in dependency)
In application.properties, you will add port details for h2 server like
h2-server:
port: 8081
Here, now, the H2 console will be available at http://localhost:8081
Following properties can be removed
# h2:
# console:
# enabled: true
# path: /h2
# settings:
# web-allow-others: true
For Reference: https://github.com/donthadineshkumar/webflux-netty-server-h2-example.git

How to configure a Spring Boot project correctly to work with Quartz and MySQL?

What I did is:
Created a Spring Boot (v2.1.8) Gradle project with Web, JPA, MySQL and Quartz as dependencies.
Then Added following properties on application.properties file
spring.application.name=QuartzTestWithMySQL
server.port=8081
## Data source
#docker run -d --rm -p 3306:3306 --name=mysql-docker -e MYSQL_ROOT_PASSWORD=root -e MYSQL_USER=test -e MYSQL_PASSWORD=test -e MYSQL_DATABASE=testDB mysql:latest
spring.datasource.name = myDS
spring.datasource.url=jdbc:mysql://localhost:3306/testDB
spring.datasource.username=test
spring.datasource.password=test
## Hibernate Properties
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = create-drop
## QuartzProperties
#spring.quartz.job-store-type=memory
spring.quartz.job-store-type=jdbc
spring.quartz.properties.org.quartz.threadPool.threadCount=5
#spring.quartz.jdbc.initialize-schema=always
#spring.quartz.properties.org.quartz.scheduler.instanceName = MyScheduler
#spring.quartz.properties.org.quartz.threadPool.threadCount = 3
#spring.quartz.properties.org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
spring.quartz.properties.org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
#spring.quartz.properties.org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
spring.quartz.properties.org.quartz.jobStore.tablePrefix = QRTZ_
spring.quartz.properties.org.quartz.jobStore.dataSource = myDS
build.gradle file is:
plugins {
id 'org.springframework.boot' version '2.1.8.RELEASE'
id 'io.spring.dependency-management' version '1.0.8.RELEASE'
id 'java'
}
group = 'com.onssoftware'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-quartz'
implementation 'org.springframework.boot:spring-boot-starter-web'
runtimeOnly 'mysql:mysql-connector-java'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
Then created following job class:
public class Bismillah implements Job {
#Override
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("Assalamu Alaikum");
}
}
Then created a controller like:
#RestController
public class SchedulerTestController {
#Autowired
private Scheduler scheduler;
#GetMapping("/scheduler")
public void testScheduler() throws SchedulerException {
// Grab the Scheduler instance from the Factory
//Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
// and start it off
//scheduler.start();
JobDetail job = JobBuilder.newJob(Bismillah.class)
.withIdentity("job1", "group1")
.storeDurably()
.withDescription("Bismillah hir rahmanir rahim")
.build();
CronTrigger cronTrigger = TriggerBuilder.newTrigger()
.withIdentity("trigger1", "group1")
.withSchedule(CronScheduleBuilder.cronSchedule("* * 11 * * ?"))
.forJob("job1", "group1")
.build();
scheduler.scheduleJob(job, cronTrigger);
}
}
Then I call from browser following url:
http://localhost:8081/scheduler
to schedule the job.
What I am getting is:
2019-09-18 12:55:31.445 INFO 10507 --- [ main] c.o.Q.QuartzTestWithMySqlApplication : No active profile set, falling back to default profiles: default
2019-09-18 12:55:32.326 INFO 10507 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-09-18 12:55:32.359 INFO 10507 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 18ms. Found 0 repository interfaces.
2019-09-18 12:55:32.810 INFO 10507 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$7395a7a2] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-09-18 12:55:33.198 INFO 10507 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8081 (http)
2019-09-18 12:55:33.235 INFO 10507 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-09-18 12:55:33.235 INFO 10507 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.24]
2019-09-18 12:55:33.344 INFO 10507 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-09-18 12:55:33.344 INFO 10507 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1841 ms
2019-09-18 12:55:33.545 INFO 10507 --- [ main] com.zaxxer.hikari.HikariDataSource : myDS - Starting...
2019-09-18 12:55:34.179 INFO 10507 --- [ main] com.zaxxer.hikari.HikariDataSource : myDS - Start completed.
2019-09-18 12:55:34.269 INFO 10507 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2019-09-18 12:55:34.344 INFO 10507 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.3.11.Final}
2019-09-18 12:55:34.345 INFO 10507 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2019-09-18 12:55:34.502 INFO 10507 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-09-18 12:55:34.682 INFO 10507 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2019-09-18 12:55:34.763 INFO 10507 --- [ main] o.h.e.j.e.i.LobCreatorBuilderImpl : HHH000421: Disabling contextual LOB creation as hibernate.jdbc.lob.non_contextual_creation is true
2019-09-18 12:55:35.033 INFO 10507 --- [ main] o.h.t.schema.internal.SchemaCreatorImpl : HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl#2007435e'
2019-09-18 12:55:35.039 INFO 10507 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-09-18 12:55:35.596 INFO 10507 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-09-18 12:55:35.764 WARN 10507 --- [ main] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2019-09-18 12:55:36.509 WARN 10507 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration$JdbcStoreTypeConfiguration$QuartzSchedulerDependencyConfiguration': Unexpected exception during bean creation; nested exception is java.lang.ArrayStoreException: sun.reflect.annotation.TypeNotPresentExceptionProxy
2019-09-18 12:55:36.518 INFO 10507 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2019-09-18 12:55:36.520 INFO 10507 --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2019-09-18 12:55:36.522 INFO 10507 --- [ main] .SchemaDropperImpl$DelayedDropActionImpl : HHH000477: Starting delayed evictData of schema as part of SessionFactory shut-down'
2019-09-18 12:55:36.541 INFO 10507 --- [ main] com.zaxxer.hikari.HikariDataSource : myDS - Shutdown initiated...
2019-09-18 12:55:36.553 INFO 10507 --- [ main] com.zaxxer.hikari.HikariDataSource : myDS - Shutdown completed.
2019-09-18 12:55:36.561 INFO 10507 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2019-09-18 12:55:36.592 INFO 10507 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-09-18 12:55:36.613 ERROR 10507 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration$JdbcStoreTypeConfiguration$QuartzSchedulerDependencyConfiguration': Unexpected exception during bean creation; nested exception is java.lang.ArrayStoreException: sun.reflect.annotation.TypeNotPresentExceptionProxy
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:528) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:845) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877) ~[spring-context-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:744) [spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:391) [spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:312) [spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) [spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1204) [spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
at com.onssoftware.QuartzTestWithMySQL.QuartzTestWithMySqlApplication.main(QuartzTestWithMySqlApplication.java:10) [classes/:na]
Caused by: java.lang.ArrayStoreException: sun.reflect.annotation.TypeNotPresentExceptionProxy
at sun.reflect.annotation.AnnotationParser.parseClassArray(AnnotationParser.java:724) ~[na:1.8.0_201]
at sun.reflect.annotation.AnnotationParser.parseArray(AnnotationParser.java:531) ~[na:1.8.0_201]
at sun.reflect.annotation.AnnotationParser.parseMemberValue(AnnotationParser.java:355) ~[na:1.8.0_201]
at sun.reflect.annotation.AnnotationParser.parseAnnotation2(AnnotationParser.java:286) ~[na:1.8.0_201]
at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:120) ~[na:1.8.0_201]
at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:72) ~[na:1.8.0_201]
at java.lang.reflect.Executable.declaredAnnotations(Executable.java:599) ~[na:1.8.0_201]
at java.lang.reflect.Executable.declaredAnnotations(Executable.java:597) ~[na:1.8.0_201]
at java.lang.reflect.Executable.getAnnotation(Executable.java:570) ~[na:1.8.0_201]
at java.lang.reflect.Method.getAnnotation(Method.java:622) ~[na:1.8.0_201]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.lambda$determineCandidateConstructors$0(AutowiredAnnotationBeanPostProcessor.java:249) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:410) ~[spring-core-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:417) ~[spring-core-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:389) ~[spring-core-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.determineCandidateConstructors(AutowiredAnnotationBeanPostProcessor.java:248) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineConstructorsFromBeanPostProcessors(AbstractAutowireCapableBeanFactory.java:1269) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1184) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
... 14 common frames omitted
Process finished with exit code 1
I think your error related to the following issue
/spring-boot/issues/18153
You could try to downgrade spring-boot to 2.1.7.RELEASE:
plugins {
id 'org.springframework.boot' version '2.1.7.RELEASE'
...
}

Hazelcast cluster not available on Eureka

I had a problem configuring simple Hazelcast cluster for existing Eureka client.
My application is simple Java SpringBoot application with Eureka discovery enabled, it is properly available for Eureka, however Hazelcast cluster is not.
This is my configuration:
hazelcast.xml
<hazelcast
xsi:schemaLocation="http://www.hazelcast.com/schema/config http://www.hazelcast.com/schema/config/hazelcast-config-3.9.xsd"
xmlns="http://www.hazelcast.com/schema/config"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<properties>
<property name="hazelcast.discovery.enabled">true</property>
<property name="hazelcast.jmx">true</property>
<property name="hazelcast.http.healthcheck.enabled">true</property>
<property name="hazelcast.rest.enabled">true</property>
<property name="hazelcast.logging.type">slf4j</property>
<property name="hazelcast.diagnostics.enabled">true</property>
<property name="hazelcast.diagnostics.metric.level">info</property>
<property name="hazelcast.name">hazelcast-cluster</property>
</properties>
<group>
<name>xxxx</name>
<password>xx</password>
</group>
<instance-name>hazelcast-cluster</instance-name>
<network>
<join>
<multicast enabled="false"/>
<tcp-ip enabled="false"/>
<aws enabled="false"/>
<discovery-strategies>
<discovery-strategy class="com.hazelcast.eureka.one.EurekaOneDiscoveryStrategy" enabled="true">
<properties>
<property name="self-registration">true</property>
<property name="namespace">hazelcast</property>
</properties>
</discovery-strategy>
</discovery-strategies>
</join>
</network>
maps....
</hazelcast>
Spring boot application:
#SpringBootApplication
#EnableAutoConfiguration ( exclude = { WebMvcAutoConfiguration.class } )
#EnableDiscoveryClient
#EnableEurekaClient
public class HazelcastClusterApplication {
public static void main( String[] args ) {
SpringApplication.run( HazelcastClusterApplication.class, args );
}
}
Configuration class:
#Configuration
public class HazelcastInstanceConfiguration {
#Bean
public HazelcastInstance hazelcastInstance(Config config, EurekaClient eurekaClient) {
EurekaOneDiscoveryStrategyFactory.setEurekaClient( eurekaClient );
return Hazelcast.newHazelcastInstance(config);
}
#Bean
public Config config() {
Config config = new ClasspathXmlConfig( "hazelcast.xml" );
return config;
}
}
bootstrap.yml
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8011/eureka/
register-with-eureka: true
spring:
mvc:
favicon:
enabled: false
application:
name: cache-server
cloud:
config:
discovery:
enabled: true
serviceId: config-server
failFast: false
retry:
initialInterval: 10000
maxInterval: 60000
maxAttempts: 12
multiplier: 10.1
config:
name: application.*, ${spring.application.name}*.*
server:
port: 7990
Maven dependencies:
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast</artifactId>
<version>3.11</version>
</dependency>
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast-spring</artifactId>
<version>3.11</version>
</dependency>
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast-eureka-one</artifactId>
<version>1.0.2</version>
</dependency>
After running, 'cache-server' application is available on Eureka, however I guess also 'hazelcast-cluster' should be available, but it is not. Or my assumption is wrong?
Startup logs:
INFO 17628 --- [ main] c.h.s.d.integration.DiscoveryService : [10.230.115.128]:5701 [xxxx] [3.11] Waiting for registration with Eureka...
INFO 17628 --- [ main] c.h.s.d.integration.DiscoveryService : [10.230.115.128]:5701 [xxxx] [3.11] Waiting for registration with Eureka...
INFO 17628 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient : DiscoveryClient_CACHE-SERVER/pc_data:cache-server:7990: registering service...
INFO 17628 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient : DiscoveryClient_CACHE-SERVER/pc_data:cache-server:7990 - registration status: 204
INFO 17628 --- [ main] c.h.s.d.integration.DiscoveryService : [10.230.115.128]:5701 [xxxx] [3.11] Waiting for registration with Eureka...
DEBUG 17628 --- [ main] c.h.i.cluster.impl.DiscoveryJoiner : [10.230.115.128]:5701 [xxxx] [3.11] This node will assume master role since no possible member where connected to.
DEBUG 17628 --- [ main] c.h.internal.cluster.ClusterService : [10.230.115.128]:5701 [xxxx] [3.11] Setting master address to [10.230.115.128]:5701
DEBUG 17628 --- [ main] c.h.i.cluster.impl.MembershipManager : [10.230.115.128]:5701 [xxxx] [3.11] Local member list join version is set to 1
DEBUG 17628 --- [ main] c.h.i.cluster.impl.DiscoveryJoiner : [10.230.115.128]:5701 [xxxx] [3.11] PostJoin master: [10.230.115.128]:5701, isMaster: true
INFO 17628 --- [ main] c.h.internal.cluster.ClusterService : [10.230.115.128]:5701 [xxxx] [3.11]
Members {size:1, ver:1} [
Member [10.230.115.128]:5701 - f6ed031e-5740-4daa-b583-5b91d98816c2 this
]
And then my cache-server application is available on Eureka, but not hazelcast-cluster as I guess it should.
Hazelcast client service logs (cutted):
2018-12-11 09:48:01.673 INFO [security-service,,,] 21496 --- [ main] com.hazelcast.client.HazelcastClient : hz.client_0 [xxxx] [3.11] A non-empty group password is configured for the Hazelcast client. Starting with Hazelcast version 3.11, clients with the same group name, but with different group passwords (that do not use authentication) will be accepted to a cluster. The group password configuration will be removed completely in a future release.
2018-12-11 09:48:01.700 INFO [security-service,,,] 21496 --- [ main] com.hazelcast.core.LifecycleService : hz.client_0 [xxxx] [3.11] HazelcastClient 3.11 (20181023 - 1500bbb) is STARTING
2018-12-11 09:48:03.233 INFO [security-service,,,] 21496 --- [ main] o.s.c.n.eureka.InstanceInfoFactory : Setting initial instance status as: STARTING
2018-12-11 09:48:03.249 INFO [security-service,,,] 21496 --- [ main] com.netflix.discovery.DiscoveryClient : Initializing Eureka in region us-east-1
2018-12-11 09:48:03.264 INFO [security-service,,,] 21496 --- [ main] c.n.d.provider.DiscoveryJerseyProvider : Using JSON encoding codec LegacyJacksonJson
2018-12-11 09:48:03.266 INFO [security-service,,,] 21496 --- [ main] c.n.d.provider.DiscoveryJerseyProvider : Using JSON decoding codec LegacyJacksonJson
2018-12-11 09:48:03.267 INFO [security-service,,,] 21496 --- [ main] c.n.d.provider.DiscoveryJerseyProvider : Using XML encoding codec XStreamXml
2018-12-11 09:48:03.267 INFO [security-service,,,] 21496 --- [ main] c.n.d.provider.DiscoveryJerseyProvider : Using XML decoding codec XStreamXml
2018-12-11 09:48:03.417 INFO [security-service,,,] 21496 --- [ main] c.n.d.s.r.aws.ConfigClusterResolver : Resolving eureka endpoints via configuration
2018-12-11 09:48:03.421 INFO [security-service,,,] 21496 --- [ main] com.netflix.discovery.DiscoveryClient : Disable delta property : false
2018-12-11 09:48:03.421 INFO [security-service,,,] 21496 --- [ main] com.netflix.discovery.DiscoveryClient : Single vip registry refresh property : null
2018-12-11 09:48:03.422 INFO [security-service,,,] 21496 --- [ main] com.netflix.discovery.DiscoveryClient : Force full registry fetch : false
2018-12-11 09:48:03.422 INFO [security-service,,,] 21496 --- [ main] com.netflix.discovery.DiscoveryClient : Application is null : false
2018-12-11 09:48:03.423 INFO [security-service,,,] 21496 --- [ main] com.netflix.discovery.DiscoveryClient : Registered Applications size is zero : true
2018-12-11 09:48:03.424 INFO [security-service,,,] 21496 --- [ main] com.netflix.discovery.DiscoveryClient : Application version is -1: true
2018-12-11 09:48:03.424 INFO [security-service,,,] 21496 --- [ main] com.netflix.discovery.DiscoveryClient : Getting all instance registry info from the eureka server
2018-12-11 09:48:03.426 INFO [security-service,,,] 21496 --- [ main] com.netflix.discovery.DiscoveryClient : The response status is 200
2018-12-11 09:48:03.426 INFO [security-service,,,] 21496 --- [ main] com.netflix.discovery.DiscoveryClient : Starting heartbeat executor: renew interval is: 5
2018-12-11 09:48:03.426 INFO [security-service,,,] 21496 --- [ main] c.n.discovery.InstanceInfoReplicator : InstanceInfoReplicator onDemand update allowed rate per min is 4
2018-12-11 09:48:03.442 INFO [security-service,,,] 21496 --- [ main] com.netflix.discovery.DiscoveryClient : Discovery Client initialized at timestamp 1544518083442 with initial instances count: 3
2018-12-11 09:48:03.488 INFO [security-service,,,] 21496 --- [ main] c.h.s.d.integration.DiscoveryService : hz.client_0 [xxxx] [3.11] Waiting for registration with Eureka...
2018-12-11 09:48:08.468 INFO [security-service,,,] 21496 --- [tbeatExecutor-0] com.netflix.discovery.DiscoveryClient : DiscoveryClient_SECURITY-SERVICE/GPLPLW2002.gft.com:security-service:8035 - Re-registering apps/SECURITY-SERVICE
2018-12-11 09:48:08.468 INFO [security-service,,,] 21496 --- [tbeatExecutor-0] com.netflix.discovery.DiscoveryClient : DiscoveryClient_SECURITY-SERVICE/GPLPLW2002.gft.com:security-service:8035: registering service...
2018-12-11 09:48:08.499 INFO [security-service,,,] 21496 --- [ main] c.h.s.d.integration.DiscoveryService : hz.client_0 [xxxx] [3.11] Waiting for registration with Eureka...
2018-12-11 09:48:08.530 INFO [security-service,,,] 21496 --- [tbeatExecutor-0] com.netflix.discovery.DiscoveryClient : DiscoveryClient_SECURITY-SERVICE/GPLPLW2002.gft.com:security-service:8035 - registration status: 204
2018-12-11 09:48:13.500 INFO [security-service,,,] 21496 --- [ main] c.h.s.d.integration.DiscoveryService : hz.client_0 [xxxx] [3.11] Waiting for registration with Eureka...
2018-12-11 09:48:18.503 INFO [security-service,,,] 21496 --- [ main] c.h.s.d.integration.DiscoveryService : hz.client_0 [xxxx] [3.11] Waiting for registration with Eureka...
2018-12-11 09:48:23.512 INFO [security-service,,,] 21496 --- [ main] c.h.s.d.integration.DiscoveryService : hz.client_0 [xxxx] [3.11] Waiting for registration with Eureka...
2018-12-11 09:48:28.513 INFO [security-service,,,] 21496 --- [ main] c.h.s.d.integration.DiscoveryService : hz.client_0 [xxxx] [3.11] Waiting for registration with Eureka...
2018-12-11 09:48:33.515 INFO [security-service,,,] 21496 --- [ main] c.h.s.d.integration.DiscoveryService : hz.client_0 [xxxx] [3.11] Waiting for registration with Eureka...
2018-12-11 09:48:33.557 INFO [security-service,,,] 21496 --- [ main] c.h.client.spi.ClientInvocationService : hz.client_0 [xxxx] [3.11] Running with 2 response threads
2018-12-11 09:48:33.742 INFO [security-service,,,] 21496 --- [ main] com.hazelcast.core.LifecycleService : hz.client_0 [xxxx] [3.11] HazelcastClient 3.11 (20181023 - 1500bbb) is STARTED
2018-12-11 09:48:33.772 DEBUG [security-service,,,] 21496 --- [ main] c.h.i.networking.nio.NioNetworking : hz.client_0 [xxxx] [3.11] TcpIpConnectionManager configured with Non Blocking IO-threading model: 1 input threads and 1 output threads
2018-12-11 09:48:33.774 DEBUG [security-service,,,] 21496 --- [ main] c.h.i.networking.nio.NioNetworking : hz.client_0 [xxxx] [3.11] IO threads selector mode is SELECT
2018-12-11 09:48:33.818 WARN [security-service,,,] 21496 --- [ient_0.cluster-] c.h.c.c.ClientConnectionManager : hz.client_0 [xxxx] [3.11] Unable to get alive cluster connection, try in 3000 ms later, attempt 1 of 2.
2018-12-11 09:48:36.822 WARN [security-service,,,] 21496 --- [ient_0.cluster-] c.h.c.c.ClientConnectionManager : hz.client_0 [xxxx] [3.11] Unable to get alive cluster connection, attempt 2 of 2.
2018-12-11 09:48:36.824 WARN [security-service,,,] 21496 --- [ient_0.cluster-] c.h.c.c.ClientConnectionManager : hz.client_0 [xxxx] [3.11] Could not connect to cluster, shutting down the client. Unable to connect to any address! The following addresses were tried: []
2018-12-11 09:48:36.828 INFO [security-service,,,] 21496 --- [clientShutdown-] com.hazelcast.core.LifecycleService : hz.client_0 [xxxx] [3.11] HazelcastClient 3.11 (20181023 - 1500bbb) is SHUTTING_DOWN
2018-12-11 09:48:36.839 INFO [security-service,,,] 21496 --- [clientShutdown-] com.netflix.discovery.DiscoveryClient : Shutting down DiscoveryClient ...
2018-12-11 09:48:36.843 INFO [security-service,,,] 21496 --- [clientShutdown-] com.netflix.discovery.DiscoveryClient : Unregistering ...
2018-12-11 09:48:36.844 WARN [security-service,,,] 21496 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: o.....org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'cacheManager' defined in class path resource
.......
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hazelcastInstance' defined in class path resource [xxxx/hazelcast/HazelcastClientConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.hazelcast.core.HazelcastInstance]: Factory method 'hazelcastInstance' threw exception; nested exception is java.lang.IllegalStateException: Unable to connect to any address! The following addresses were tried: []
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
... 150 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.hazelcast.core.HazelcastInstance]: Factory method 'hazelcastInstance' threw exception; nested exception is java.lang.IllegalStateException: Unable to connect to any address! The following addresses were tried: []
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
... 163 common frames omitted
Caused by: java.lang.IllegalStateException: Unable to connect to any address! The following addresses were tried: []
at com.hazelcast.client.connection.nio.ClusterConnector.connectToClusterInternal(ClusterConnector.java:206)
at com.hazelcast.client.connection.nio.ClusterConnector.access$400(ClusterConnector.java:56)
at com.hazelcast.client.connection.nio.ClusterConnector$2.call(ClusterConnector.java:215)
at com.hazelcast.client.connection.nio.ClusterConnector$2.call(ClusterConnector.java:211)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
at com.hazelcast.util.executor.HazelcastManagedThread.executeRun(HazelcastManagedThread.java:64)
at com.hazelcast.util.executor.HazelcastManagedThread.run(HazelcastManagedThread.java:80)
What is wrong with my configuration, is this a server problem or client?
Client configuration:
#Bean
#Autowired
public HazelcastInstance hazelcastInstance( EurekaClient eurekaClient, GroupConfig groupConfig ) {
EurekaOneDiscoveryStrategyFactory.setEurekaClient( eurekaClient );
ClientConfig config = new ClientConfig();
config.setGroupConfig( groupConfig );
config.setProperty( "hazelcast.discovery.enabled", "true" );
DiscoveryStrategyConfig discoveryStrategyConfig = new DiscoveryStrategyConfig( new EurekaOneDiscoveryStrategyFactory() );
discoveryStrategyConfig.addProperty( "use-classpath-eureka-client-props", "false" );
discoveryStrategyConfig.addProperty( "self-registration", "false" );
DiscoveryConfig discoveryConfig = new DiscoveryConfig();
discoveryConfig.addDiscoveryStrategyConfig( discoveryStrategyConfig );
config.getNetworkConfig().setDiscoveryConfig( discoveryConfig );
return HazelcastClient.newHazelcastClient( config );
}
The problem is that you use the same EurekaClient for you app discovery (port 7990) and your Hazelcast discovery (port 5701). For more information, read the related GH issue.
You can solve it in two ways:
Use the property use-metadata-for-host-and-port as described here
Use separate Eureka Client and ports for your app and Hazelcast
EDIT: The use-metadata-for-host-and-port will be released in hazelcast-eureka:1.0.3 soon. I've also prepared Hazelcast Eureka Code Sample.
Have you seen the example configs in Eureka plugin repo and also the code sample with Eureka? I see there are some differences in the configs with yours. Please check and let me know if you still have problems.

Spring Session Boot Error - No session repository could be auto-configured, check your configuration (session store type is 'jdbc')

I am trying to create a simple Spring Boot Session project. It's the basic setup from Spring Initializr. I am getting following errors:
2018-06-20 12:59:24.318 INFO 8108 --- [ main] c.j.s.SpringSessionExampleApplication : Starting SpringSessionExampleApplication on pankaj with PID 8108 (/Users/pankaj/Documents/workspace-sts-3.9.4.RELEASE/Spring-Session-Example/target/classes started by pankaj in /Users/pankaj/Documents/workspace-sts-3.9.4.RELEASE/Spring-Session-Example)
2018-06-20 12:59:24.329 INFO 8108 --- [ main] c.j.s.SpringSessionExampleApplication : No active profile set, falling back to default profiles: default
2018-06-20 12:59:24.372 INFO 8108 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#39de3d36: startup date [Wed Jun 20 12:59:24 IST 2018]; root of context hierarchy
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.springframework.cglib.core.ReflectUtils$1 (file:/Users/pankaj/.m2/repository/org/springframework/spring-core/5.0.7.RELEASE/spring-core-5.0.7.RELEASE.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
WARNING: Please consider reporting this to the maintainers of org.springframework.cglib.core.ReflectUtils$1
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
2018-06-20 12:59:25.208 INFO 8108 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2018-06-20 12:59:25.226 INFO 8108 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-06-20 12:59:25.226 INFO 8108 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.31
2018-06-20 12:59:25.230 INFO 8108 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/Users/pankaj/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.]
2018-06-20 12:59:25.297 INFO 8108 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-06-20 12:59:25.297 INFO 8108 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 931 ms
2018-06-20 12:59:25.407 INFO 8108 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-06-20 12:59:25.411 INFO 8108 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-06-20 12:59:25.411 INFO 8108 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-06-20 12:59:25.411 INFO 8108 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-06-20 12:59:25.411 INFO 8108 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-06-20 12:59:25.500 INFO 8108 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-06-20 12:59:25.687 INFO 8108 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#39de3d36: startup date [Wed Jun 20 12:59:24 IST 2018]; root of context hierarchy
2018-06-20 12:59:25.731 INFO 8108 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/messages],methods=[POST]}" onto public java.lang.String com.journaldev.spring.HomeController.saveMessage(java.lang.String,javax.servlet.http.HttpServletRequest)
2018-06-20 12:59:25.732 INFO 8108 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/],methods=[GET]}" onto public java.lang.String com.journaldev.spring.HomeController.home(org.springframework.ui.Model,javax.servlet.http.HttpSession)
2018-06-20 12:59:25.734 INFO 8108 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-06-20 12:59:25.735 INFO 8108 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-06-20 12:59:25.757 INFO 8108 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-06-20 12:59:25.758 INFO 8108 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-06-20 12:59:25.844 INFO 8108 --- [ main] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page template: index
2018-06-20 12:59:26.005 WARN 8108 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.session.SessionAutoConfiguration$ServletSessionRepositoryValidator': Invocation of init method failed; nested exception is org.springframework.boot.autoconfigure.session.SessionRepositoryUnavailableException: No session repository could be auto-configured, check your configuration (session store type is 'jdbc')
2018-06-20 12:59:26.006 INFO 8108 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
2018-06-20 12:59:26.008 INFO 8108 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2018-06-20 12:59:26.023 INFO 8108 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-06-20 12:59:26.032 ERROR 8108 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.session.SessionAutoConfiguration$ServletSessionRepositoryValidator': Invocation of init method failed; nested exception is org.springframework.boot.autoconfigure.session.SessionRepositoryUnavailableException: No session repository could be auto-configured, check your configuration (session store type is 'jdbc')
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:138) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:424) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1700) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:581) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:503) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at com.journaldev.spring.SpringSessionExampleApplication.main(SpringSessionExampleApplication.java:10) [classes/:na]
Caused by: org.springframework.boot.autoconfigure.session.SessionRepositoryUnavailableException: No session repository could be auto-configured, check your configuration (session store type is 'jdbc')
at org.springframework.boot.autoconfigure.session.SessionAutoConfiguration$AbstractSessionRepositoryValidator.checkSessionRepository(SessionAutoConfiguration.java:257) ~[spring-boot-autoconfigure-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:365) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:308) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:135) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
... 18 common frames omitted
My application.properties:
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/SpringSessionDB
spring.datasource.username=pankaj
spring.datasource.password=pankaj
spring.session.store-type=jdbc
spring.session.jdbc.initialize-schema=always
Dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-core</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
I am not sure what is missing here?
You are missing the spring-session-jdbc dependency so the JdbcOperationsSessionRepository isn't present on the classpath. Your dependency management provides only spring-session-core dependency, which provides only Spring Session core API - the concrete SessionRepository implementations are placed in dedicated modules i.e. spring-session-data-redis, spring-session-jdbc, spring-session-hazelcast etc.
Once you do that, you can also remove the spring.session.store-type configuration property. As long as you have a single SessionRepository implementation on the classpath, Spring Boot will be able to deduce which one to auto-configure without you having to provide spring.session.store-type.
Having said that, Initializr should be able to include spring-session-jdbc for you however I believe you originally only selected Web, Session and MySQL options when creating project on Initialzr. Together with Session option, you should also select the store you intend to use (like JDBC in this case) so the Initializr can include the required Spring Session module.
On a final note, the arrangement with Spring Session modules changed in Spring Session 2.0, as previously all the code and SessionRepository implementations were placed in spring-session artifact which doesn't exist anymore in Spring Session 2.0. You can learn more about this in in the reference manual and have been mentioned in the 2.0.0.RELEASE announcement.

Resources