I am using Hibernate 5.4.0.Final and Spring 4.3.13.RELEASE I have written following code
#Bean
public SessionFactory sharedDataSessionFactory()
{
LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(sharedDataSource());
builder.scanPackages("com.some.package", "scom.some.package1");
hibernateProperties.put("hibernate.dialect", MySQL5InnoDBDialect.class);
hibernateProperties.put("hibernate.id.new_generator_mappings", false);
hibernateProperties.put("hibernate.show_sql", false);
hibernateProperties.put("hibernate.cache.use_second_level_cache", false);
hibernateProperties.put("hibernate.cache.use_query_cache", false);
hibernateProperties.put("hibernate.jdbc.batch_size", 25);
builder.addProperties(hibernateProperties);
return builder.buildSessionFactory();
}
#Bean
public PlatformTransactionManager transactionManagerSharedData() {
return new HibernateTransactionManager(sharedDataSessionFactory());
}
But when I run test code it gives exception like this
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.transaction.PlatformTransactionManager]: Factory method 'transactionManagerSharedData' threw exception; nested exception is java.lang.ClassCastException: org.springframework.orm.hibernate5.LocalSessionFactoryBean$$EnhancerBySpringCGLIB$$d6b39340 cannot be cast to org.hibernate.SessionFactory
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
... 42 more
Caused by: java.lang.ClassCastException: org.springframework.orm.hibernate5.LocalSessionFactoryBean$$EnhancerBySpringCGLIB$$d6b39340 cannot be cast to org.hibernate.SessionFactory
at se.ss.some.backend.config.HibernateConfig$$EnhancerBySpringCGLIB$$2342b23c.sharedDataSessionFactory(<generated>)
at se.ss.some.backend.config.HibernateConfig.transactionManagerSharedData(HibernateConfig.java:106)
at se.ss.some.backend.config.HibernateConfig$$EnhancerBySpringCGLIB$$2342b23c.CGLIB$transactionManagerSharedData$5(<generated>)
at se.ss.some.backend.config.HibernateConfig$$EnhancerBySpringCGLIB$$2342b23c$$FastClassBySpringCGLIB$$7c29b43a.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358)
at se.mindspot.tender.backend.config.HibernateConfig$$EnhancerBySpringCGLIB$$2342b23c.transactionManagerSharedData(<generated>
)
But my application run fine with this code. What is the cause to cast this class???
Related
I have created a tasklet to download a file at SFTP server using Spring-Integration-Batch. While running the batch, it seems remote directory is not setting correctly in AbstractInboundFileSynchronizer because of which program is trying to synchronize null with local directory.
When I tried calling afterPropertiesSet() of AbstractInboundFileSynchronizer just before synchronizeToLocalDirectory(), then it downloaded the files with warning as "No beanFactory".
Below is the tasklet I am running:
public class FtpFileDownloadTasklet implements Tasklet {
#Value("${ftp.source.directory}")
private String remoteDirectory;
#Value("${ftp.dest.directory}")
private String localDirectory;
#Value("${ftp.source.file.extn}")
private String sourceFileExtn;
#Autowired
private SessionFactory<LsEntry> sftpSessionFactory;
private SftpInboundFileSynchronizer fileSynchronizer;
#Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
if (sftpSessionFactory.getSession().isOpen()) {
fileSynchronizer = new SftpInboundFileSynchronizer(sftpSessionFactory);
fileSynchronizer.setDeleteRemoteFiles(false);
fileSynchronizer.setFilter(new SftpSimplePatternFileListFilter("*" + sourceFileExtn));
fileSynchronizer.setRemoteDirectory(remoteDirectory);
fileSynchronizer.synchronizeToLocalDirectory(new File(localDirectory));
}
return RepeatStatus.FINISHED;
}
}
My Session factory:
#Bean
public SessionFactory<LsEntry> sftpSessionFactory() {
DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory();
factory.setHost(host);
factory.setPort(port);
factory.setUser(username);
factory.setPassword(password);
factory.setAllowUnknownKeys(true);
return new CachingSessionFactory<LsEntry>(factory);
}
But, without a call to afterPropertiesSet(), I am getting below error:
org.springframework.messaging.MessagingException: Problem occurred while synchronizing 'null' to local directory; nested exception is org.springframework.messaging.MessagingException: Failed to execute on session; nested exception is org.springframework.core.NestedIOException: Failed to list files; nested exception is 4:
at org.springframework.integration.file.remote.synchronizer.AbstractInboundFileSynchronizer.synchronizeToLocalDirectory(AbstractInboundFileSynchronizer.java:315) ~[spring-integration-file-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.integration.file.remote.synchronizer.AbstractInboundFileSynchronizer.synchronizeToLocalDirectory(AbstractInboundFileSynchronizer.java:293) ~[spring-integration-file-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at com.ftp.demo.tasklet.FtpFileDownloadTasklet.execute(FtpFileDownloadTasklet.java:52) ~[classes/:na]
at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:407) ~[spring-batch-core-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:331) ~[spring-batch-core-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:140) ~[spring-tx-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:273) ~[spring-batch-core-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:82) ~[spring-batch-core-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:375) ~[spring-batch-infrastructure-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215) ~[spring-batch-infrastructure-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:145) ~[spring-batch-infrastructure-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:258) ~[spring-batch-core-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:203) ~[spring-batch-core-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:148) [spring-batch-core-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.batch.core.job.AbstractJob.handleStep(AbstractJob.java:399) [spring-batch-core-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.batch.core.job.SimpleJob.doExecute(SimpleJob.java:135) [spring-batch-core-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:313) [spring-batch-core-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:144) [spring-batch-core-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50) [spring-core-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:137) [spring-batch-core-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at com.ftp.demo.main.SpringBatchIntegrationftpDemoApplication.main(SpringBatchIntegrationftpDemoApplication.java:44) [classes/:na]
Caused by: org.springframework.messaging.MessagingException: Failed to execute on session; nested exception is org.springframework.core.NestedIOException: Failed to list files; nested exception is 4:
at org.springframework.integration.file.remote.RemoteFileTemplate.execute(RemoteFileTemplate.java:446) ~[spring-integration-file-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.integration.file.remote.synchronizer.AbstractInboundFileSynchronizer.synchronizeToLocalDirectory(AbstractInboundFileSynchronizer.java:308) ~[spring-integration-file-5.1.4.RELEASE.jar:5.1.4.RELEASE]
... 20 common frames omitted
Caused by: org.springframework.core.NestedIOException: Failed to list files; nested exception is 4:
at org.springframework.integration.sftp.session.SftpSession.list(SftpSession.java:103) ~[spring-integration-sftp-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.integration.sftp.session.SftpSession.list(SftpSession.java:50) ~[spring-integration-sftp-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.integration.file.remote.session.CachingSessionFactory$CachedSession.list(CachingSessionFactory.java:230) ~[spring-integration-file-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.integration.file.remote.synchronizer.AbstractInboundFileSynchronizer.transferFilesFromRemoteToLocal(AbstractInboundFileSynchronizer.java:323) ~[spring-integration-file-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.integration.file.remote.synchronizer.AbstractInboundFileSynchronizer.lambda$synchronizeToLocalDirectory$0(AbstractInboundFileSynchronizer.java:309) ~[spring-integration-file-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.integration.file.remote.RemoteFileTemplate.execute(RemoteFileTemplate.java:437) ~[spring-integration-file-5.1.4.RELEASE.jar:5.1.4.RELEASE]
... 21 common frames omitted
Caused by: com.jcraft.jsch.SftpException:
at com.jcraft.jsch.ChannelSftp.ls(ChannelSftp.java:1747) ~[jsch-0.1.55.jar:na]
at com.jcraft.jsch.ChannelSftp.ls(ChannelSftp.java:1553) ~[jsch-0.1.55.jar:na]
at org.springframework.integration.sftp.session.SftpSession.list(SftpSession.java:91) ~[spring-integration-sftp-5.1.4.RELEASE.jar:5.1.4.RELEASE]
... 26 common frames omitted
Caused by: java.lang.NullPointerException: null
at com.jcraft.jsch.ChannelSftp.remoteAbsolutePath(ChannelSftp.java:2943) ~[jsch-0.1.55.jar:na]
at com.jcraft.jsch.ChannelSftp.ls(ChannelSftp.java:1572) ~[jsch-0.1.55.jar:na]
... 28 common frames omitted
In the execute method instead of
fileSynchronizer.synchronizeToLocalDirectory(new File(localDirectory));
}
Use
fileSynchronizer.setFilter(
new SftpPersistentAcceptOnceFileListFilter(new SimpleMetadataStore(), "rotate")
);
It will sync your local directory with a remote file.
These are the beans I have created and trying to use Hikari in my project but getting the errors.
LocalContainerEntityManagerFactoryBean Configuration method:
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.xyz.entitiy" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
DataSource configuration method:
#Bean
public DataSource dataSource() {
HikariConfig config = new HikariConfig(); config.setDataSourceClassName("org.postgresql.ds.PGSimpleDataSource");
config.setDriverClassName("org.postgresql.Driver");
config.setJdbcUrl("jdbc:postgresql://localhost:5432/abc");
config.setUsername("abc");
config.setPassword("abc");
return new HikariDataSource(config);
}
PlatformTransactionManager configuration method:
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
PersistenceExceptionTranslationPostProcessor configuration method:
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
Properties configuration method:
private Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
return properties;
}
I'm trying to migrate from BoneCP to HikariCP for PostgreSQL. But facing this issue:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in com.xyz.ets.persistence.config.PersistenceContext: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]: Factory method 'entityManagerFactory' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in com.xyz.ets.persistence.config.PersistenceContext: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is com.zaxxer.hikari.pool.HikariPool$PoolInitializationException: Failed to initialize pool: Method org.postgresql.jdbc4.Jdbc4Connection.isValid(int) is not yet implemented.
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]: Factory method 'entityManagerFactory' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in com.xyz.ets.persistence.config.PersistenceContext: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is com.zaxxer.hikari.pool.HikariPool$PoolInitializationException: Failed to initialize pool: Method org.postgresql.jdbc4.Jdbc4Connection.isValid(int) is not yet implemented.
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is com.zaxxer.hikari.pool.HikariPool$PoolInitializationException: Failed to initialize pool: Method org.postgresql.jdbc4.Jdbc4Connection.isValid(int) is not yet implemented.
Caused by: java.sql.SQLFeatureNotSupportedException: Method org.postgresql.jdbc4.Jdbc4Connection.isValid(int) is not yet implemented.
Sep 25, 2018 12:47:28 AM org.apache.catalina.core.StandardContext loadOnStartup
pom.file dependency using:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.3-1100-jdbc41</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.6.1</version>
</dependency>
spring configuration: Trying to instantiate a JmsMessageListenerContainerFactory Bean that will use a specific connection factory bean instance using annotations.
#Configuration
public class DemoJmsConfig {
#Value("${jms.context.factory}")
private String initialContextFactory;
#Value("${jms.provider.url}")
String jmsProviderUrl;
//Inbound
#Value("${jms.inbound.qcf.userName}")
private String inboundQcfUserName;
#Value("${jms.inbound.qcf.password}")
private String inboundQcfPassword;
#Value("${jms.inbound.queue.connectionfactory}")
private String inboundQueueConnectionFactory;
#Value("${jms.inbound.queue.name}")
private String inboundQueueName;
#Value("${jms.inbound.initial.cache.size}")
private String inboundInitCacheSize;
//Outbound
#Value("${jms.outbound.topic.connectionfactory}")
private String outboundTopicConnectionFactory;
#Value("${jms.outbound.topic.name}")
private String outboundTopicName;
#Value("${jms.outbound.tcf.userName}")
private String outboundTcfUserName;
#Value("${jms.outbound.tcf.password}")
private String outboundTcfPassword;
#Value("${jms.outbound.initial.cache.size}")
private String outboundInitCacheSize;
#Bean
public InitialContext initialContext() throws NamingException {
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY,
initialContextFactory);
props.put(Context.PROVIDER_URL, jmsProviderUrl);
// Create the initial context from the properties we just created
return new InitialContext(props);
}
#Bean(name="inboundConnectionFactory")
#Qualifier("inboundConnectionFactory")
public ConnectionFactory inboundConnectionFactory() throws NamingException {
//Create a Connection Factory adapter with user credentials
UserCredentialsConnectionFactoryAdapter uccfa = new UserCredentialsConnectionFactoryAdapter();
ConnectionFactory cf = (ConnectionFactory) initialContext().lookup(inboundQueueConnectionFactory);
uccfa.setTargetConnectionFactory(cf);
uccfa.setUsername(inboundQcfUserName);
uccfa.setPassword(inboundQcfPassword);
CachingConnectionFactory ccf = new CachingConnectionFactory();
if(inboundInitCacheSize != null && Integer.parseInt(inboundInitCacheSize) > 0){
ccf.setSessionCacheSize(Integer.parseInt(inboundInitCacheSize)); //Default is 1
}
ccf.setTargetConnectionFactory(uccfa);
return ccf;
}
#Bean(name="inboundJMSTemplate")
#Qualifier("inboundJMSTemplate")
public JmsTemplate inboundJMSTemplate(#Qualifier("inboundConnectionFactory") ConnectionFactory inboundConnectionFactory ) throws NamingException{
JmsTemplate jmsTemplate = new JmsTemplate();
jmsTemplate.setConnectionFactory(inboundConnectionFactory);
jmsTemplate.setDefaultDestinationName(inboundQueueName);
return jmsTemplate;
}
#Bean(name="inboundJmsListenerContainerFactory")
#Qualifier("inboundJmsListenerContainerFactory")
public JmsListenerContainerFactory<?> inboundJmsListenerContainerFactory(
DefaultJmsListenerContainerFactoryConfigurer configurer,
#Qualifier("inboundConnectionFactory") ConnectionFactory inboundConnectionFactory)
throws NamingException {
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
// This provides all boot's default to this factory, including the
// message converter
configurer.configure(factory, inboundConnectionFactory);
// You could still override some of Boot's default if necessary.
return factory;
}
#Bean(name="outboundConnectionFactory")
#Qualifier("outboundConnectionFactory")
public ConnectionFactory outboundConnectionFactory() throws NamingException {
//Create a Connection Factory adapter with user credentials
UserCredentialsConnectionFactoryAdapter uccfa = new UserCredentialsConnectionFactoryAdapter();
ConnectionFactory cf = (ConnectionFactory) initialContext().lookup(outboundTopicConnectionFactory);
uccfa.setTargetConnectionFactory(cf);
uccfa.setUsername(outboundTcfUserName);
uccfa.setPassword(outboundTcfPassword);
CachingConnectionFactory ccf = new CachingConnectionFactory();
if(outboundInitCacheSize != null && Integer.parseInt(outboundInitCacheSize) > 0){
ccf.setSessionCacheSize(Integer.parseInt(outboundInitCacheSize)); //Default is 1
}
ccf.setTargetConnectionFactory(uccfa);
return ccf;
}
#Bean(name="outboundErrorJMSTemplate")
#Qualifier("outboundErrorJMSTemplate")
public JmsTemplate outboundErrorJMSTemplate(#Qualifier("outboundConnectionFactory") ConnectionFactory outboundConnectionFactory ) throws NamingException{
JmsTemplate jmsTemplate = new JmsTemplate();
jmsTemplate.setConnectionFactory(outboundConnectionFactory);
jmsTemplate.setDefaultDestinationName(outboundTopicName);
return jmsTemplate;
}
}
Expected result: The JmsListenerContainerFactory is instantiated.
Actual:
*************************** APPLICATION FAILED TO START
***************************
Description:
Parameter 1 of method jmsListenerContainerFactory in org.springframework.boot.autoconfigure.jms.JmsAnnotationDrivenConfiguration required a single bean, but 2 were found:
- inboundConnectionFactory: defined by method 'inboundConnectionFactory' in class path resource [com/example/demo/config/DemoJmsConfig.class]
- outboundConnectionFactory: defined by method 'outboundConnectionFactory' in class path resource [com/example/demo/config/DemoJmsConfig.class]
Action:
Consider marking one of the beans as #Primary, updating the consumer to accept multiple beans, or using #Qualifier to identify the bean that should be consumed
[WARNING] java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run(AbstractRunMojo.java:527) at java.lang.Thread.run(Thread.java:745) Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'jmsListenerContainerFactory' defined in class path resource [org/springframework/boot/autoconfigure/jms/JmsAnnotationDrivenConfiguration.class]: Unsatisfied dependency expressed through method 'jmsListenerContainerFactory' parameter 1; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.jms.ConnectionFactory' available: expected single matching bean but found 2: inboundConnectionFactory,outboundConnectionFactory at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749) at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:467) 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:197) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) at com.example.demo.DemoApplication.main(DemoApplication.java:10) ... 6 more Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.jms.ConnectionFactory' available: expected single matching bean but found 2: inboundConnectionFactory,outboundConnectionFactory at org.springframework.beans.factory.config.DependencyDescriptor.resolveNotUnique(DependencyDescriptor.java:173) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1116) 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) ... 25 more
I have tried specifying qualifiers, bean names.. still getting errors. Can anyone suggest what I should do to resolve this. I need both the inbound and outbound connections since the application will consume and publish
resolved by adding #Primary to inbound Connection factory
Check this question Spring Boot multiple JMS connections that can help you. If in your case are using a mix of Spring XML and annotations to make a connection factory, maybe you can have problems with SpringBoot, in this case thy disable autostart of spring-boot-jms with this in your application:
#SpringBootApplication(exclude = {JmsAutoConfiguration.class})
this was my case.
I'm having a problem with my testing. I'm using java spring and trying to run junit test to check if my server is alive.
This the test I'm trying:
#RunWith(SpringJUnit4ClassRunner::class)
#ContextConfiguration(classes = arrayOf(ServiceContext::class,DatabaseContext::class))
#Transactional
open class newtest : AbstractTestController(){
#Test
fun echoTest() {
mockMvc.perform(get("/echo").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk)
}
}
This is the AbstractTestController class that my newtest class is extending:
#WebAppConfiguration
abstract class AbstractTestController : DatabaseInitializedTest() {
#Autowired
lateinit var webAppContext: WebApplicationContext
lateinit var mockMvc: MockMvc
#Autowired
lateinit var authHelper: OAuthHelper
#Autowired
private lateinit var userService: UserService
fun adminToken(username: String) = authHelper.addBearerToken(userService.getUserByUsername(username), *AuthoritiesService.adminAuthorities.toTypedArray())
fun clientItToken(username: String) = authHelper.addBearerToken(userService.getUserByUsername(username), *AuthoritiesService.clientItAuthorities.toTypedArray())
fun clientManagerToken(username: String) = authHelper.addBearerToken(userService.getUserByUsername(username), *AuthoritiesService.clientManagerAuthorities.toTypedArray())
fun endUserToken(username: String) = authHelper.addBearerToken(userService.getUserByUsername(username), *AuthoritiesService.endUserAuthorities.toTypedArray())
#Autowired
lateinit var mapper: ObjectMapper
fun <T> ResultActions.and200ReturnClass(clazz: TypeReference<T>): ResultActions {
if (this.andReturn().response.status == HttpServletResponse.SC_OK
&& this.andReturn().response.contentAsString.isNotEmpty()) {
mapper.readValue<T>(this.andReturn().response.contentAsString, clazz)!!
}
return this
}
#Before
fun initialize() {
mockMvc = MockMvcBuilders
.webAppContextSetup(webAppContext)
.apply<DefaultMockMvcBuilder>(SecurityMockMvcConfigurers.springSecurity())
.alwaysDo<DefaultMockMvcBuilder>(MockMvcResultHandlers.print())
.build()
}
}
My configuration:
#Configuration
#Import(value = *arrayOf(
OAuth2ServerConfiguration::class,
OAuth2ServerConfiguration.AuthorizationServerConfiguration::class,
OAuth2ServerConfiguration.ResourceServerConfiguration::class,
SecurityConfig::class,
OAuthHelper::class,
WebConfig::class,
DatabaseInitializator::class,
LowerCaser::class))
#ComponentScan("com.hyg","com.hyg.service", "com.hyg.web", "com.hyg.utils")
#EnableAutoConfiguration
#EnableAspectJAutoProxy(proxyTargetClass = true)
open class ServiceContext
#Configuration
#EnableJpaRepositories("com.hyg")
#EnableTransactionManagement
#EnableAutoConfiguration
#PropertySource("classpath:application.properties")
open class DatabaseContext {
val DATA_PACKAGE = "com.hyg.data"
val INTERCEPTOR_KEY = "hibernate.ejb.interceptor"
#Value("\${spring.datasource.username:${Const.NONE}}")
lateinit var username: String
#Value("\${spring.datasource.url}")
lateinit var url: String
#Value("\${spring.datasource.driverClassName}")
lateinit var driverClass: String
#Value("\${spring.datasource.password}")
lateinit var password: String
#Bean
#Primary
open fun objectMapper(): ObjectMapper {
val mapper = ObjectMapper()
mapper.registerModule(KotlinModule())
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true)
mapper.configure(MapperFeature.USE_STD_BEAN_NAMING, true)
mapper.configure(DeserializationFeature.ACCEPT_FLOAT_AS_INT, false)
mapper.registerModule(JavaTimeModule())
mapper.registerModule(localDateTimeSerializer())
return mapper
}
#Bean
open fun localDateTimeSerializer(): SimpleModule {
val localDateTimeSerializer = SimpleModule()
val serializer = LocalDateTimeSerializer(
DateTimeFormatter.ofPattern(Const.DATE_TIME_PATTERN))
val deserializer = LocalDateTimeDeserializer(
DateTimeFormatter.ofPattern(Const.DATE_TIME_PATTERN))
localDateTimeSerializer.addSerializer(LocalDateTime::class.java, serializer)
localDateTimeSerializer.addDeserializer(LocalDateTime::class.java, deserializer)
return localDateTimeSerializer
}
#Bean
open fun dataSource(): DataSource {
val ds = DataSourceBuilder.create().driverClassName(driverClass).username(username).password(password).url(url).build()
val proxy = ProxyDataSource()
proxy.setDataSource(ds)
proxy.setListener(DataSourceQueryCountListener())
return proxy
}
#Bean
open fun entityManagerFactory(
factory: EntityManagerFactoryBuilder, dataSource: DataSource,
properties: JpaProperties): LocalContainerEntityManagerFactoryBean {
val jpaProperties = HashMap<String, Any>()
jpaProperties.putAll(properties.getHibernateProperties(dataSource))
jpaProperties.put(INTERCEPTOR_KEY, hibernateInterceptor())
return factory.dataSource(dataSource).packages(DATA_PACKAGE)
.properties(jpaProperties as MutableMap<String, *>)
.build()
}
#Bean
open fun hibernateInterceptor(): HibernateStatisticsInterceptor {
return HibernateStatisticsInterceptor()
}
#Bean
open fun requestStatisticsInterceptor(): RequestStatisticsInterceptor {
return RequestStatisticsInterceptor()
}
}
This is the full Error I'm getting:
2017-11-17 20:03:52.477 WARN --- [ main] o.s.w.c.s.GenericWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.actuate.autoconfigure.EndpointMBeanExportAutoConfiguration': Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.autoconfigure.EndpointMBeanExportAutoConfiguration$$EnhancerBySpringCGLIB$$ecfe2bfa]: Constructor threw exception; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.fasterxml.jackson.databind.ObjectMapper' available: expected single matching bean but found 3: objectMapper,halObjectMapper,_halObjectMapper
2017-11-17 20:03:52.477 INFO --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
2017-11-17 20:03:52.499 INFO --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2017-11-17 20:03:52.508 ERROR --- [ main] o.s.test.context.TestContextManager : Caught exception while allowing TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener#6b19b79] to prepare test instance [com.hyginex.Integration.newtest#7a08da83]
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
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.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.actuate.autoconfigure.EndpointMBeanExportAutoConfiguration': Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.autoconfigure.EndpointMBeanExportAutoConfiguration$$EnhancerBySpringCGLIB$$ecfe2bfa]: Constructor threw exception; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.fasterxml.jackson.databind.ObjectMapper' available: expected single matching bean but found 3: objectMapper,halObjectMapper,_halObjectMapper
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:279)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1154)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1056)
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:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.test.context.web.AbstractGenericWebContextLoader.loadContext(AbstractGenericWebContextLoader.java:134)
at org.springframework.test.context.web.AbstractGenericWebContextLoader.loadContext(AbstractGenericWebContextLoader.java:61)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:108)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:251)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
... 24 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.autoconfigure.EndpointMBeanExportAutoConfiguration$$EnhancerBySpringCGLIB$$ecfe2bfa]: Constructor threw exception; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.fasterxml.jackson.databind.ObjectMapper' available: expected single matching bean but found 3: objectMapper,halObjectMapper,_halObjectMapper
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:122)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:271)
... 41 common frames omitted
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.fasterxml.jackson.databind.ObjectMapper' available: expected single matching bean but found 3: objectMapper,halObjectMapper,_halObjectMapper
at org.springframework.beans.factory.config.DependencyDescriptor.resolveNotUnique(DependencyDescriptor.java:172)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1114)
at org.springframework.beans.factory.support.DefaultListableBeanFactory$DependencyObjectProvider.getIfAvailable(DefaultListableBeanFactory.java:1643)
at org.springframework.boot.actuate.autoconfigure.EndpointMBeanExportAutoConfiguration.<init>(EndpointMBeanExportAutoConfiguration.java:63)
at org.springframework.boot.actuate.autoconfigure.EndpointMBeanExportAutoConfiguration$$EnhancerBySpringCGLIB$$ecfe2bfa.<init>(<generated>)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142)
... 43 common frames omitted
Hope it will help to solve my problem.
I tried so far to put #Primary on the Bean that make the ObjectMapper or to add those annotation #Order
#ConditionalOnMissingBean but it didn't work...
Thank you
You have several beans with the type ObjectMapper in the Spring Context. Try to add the annotation #Qualifier("objectMapper") for mapper (in AbstractTestController) or rename it to objectMapper:
#WebAppConfiguration
abstract class AbstractTestController : DatabaseInitializedTest() {
...
#Qualifier("objectMapper")
#Autowired
lateinit var mapper: ObjectMapper
...
}
or
#WebAppConfiguration
abstract class AbstractTestController : DatabaseInitializedTest() {
...
#Autowired
lateinit var objectMapper: ObjectMapper
...
}
When my springboot application startup, I have the following exception. I didn't found where is problem, if someone has an idea... thanks by advance
2015-05-18 14:50:49,313 DEBUG c.q.q.Application:50 - Running with Spring Boot v1.2.3.RELEASE, Spring v4.1.6.RELEASE
2015-05-18 14:50:51,848 DEBUG o.j.logging:33 - Logging Provider: org.jboss.logging.Slf4jLoggerProvider
2015-05-18 14:50:51,991 DEBUG c.q.q.c.AsyncConfiguration:36 - Creating Async Task Executor
2015-05-18 14:50:52,126 INFO c.q.q.Application:60 - Running with Spring profile(s) : [dev]
2015-05-18 14:50:52,752 DEBUG c.q.q.c.MetricsConfiguration:71 - Registring JVM gauges
2015-05-18 14:50:54,870 ERROR o.s.b.c.e.t.TomcatStarter:62 - Error starting Tomcat context: org.springframework.beans.factory.BeanCreationException
2015-05-18 14:50:54,914 WARN o.s.b.c.e.AnnotationConfigEmbeddedWebApplicationContext:487 - Exception encountered during context initialization - cancelling refresh attempt
org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.boot.context.embedded.EmbeddedServletContainerException: Unable to start embedded Tomcat
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:133) [spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:474) ~[spring-context-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) [spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686) [spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320) [spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
at com.qwam.qes.Application.main(Application.java:84) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_25]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_25]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_25]
at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_25]
at org.springframework.boot.maven.RunMojo$LaunchRunner.run(RunMojo.java:418) [spring-boot-maven-plugin-1.2.3.RELEASE.jar:1.2.3.RELEASE]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_25]
Caused by: org.springframework.boot.context.embedded.EmbeddedServletContainerException: Unable to start embedded Tomcat
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.initialize(TomcatEmbeddedServletContainer.java:98) ~[spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.<init>(TomcatEmbeddedServletContainer.java:75) ~[spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory.getTomcatEmbeddedServletContainer(TomcatEmbeddedServletContainerFactory.java:378) ~[spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory.getEmbeddedServletContainer(TomcatEmbeddedServletContainerFactory.java:155) ~[spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:157) [spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:130) [spring-boot-1.2.3.RELEASE.jar:1.2.3.RELEASE]
... 11 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.setFilterChainProxySecurityConfigurer(org.springframework.security.config.annotation.ObjectPostProcessor,java.util.List) throws java.lang.Exception; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.setAuthenticationConfiguration(org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration); nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration.setGlobalAuthenticationConfigurers(java.util.List) throws java.lang.Exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'springBootAuthenticationConfigurerAdapter' defined in class path resource [org/springframework/boot/autoconfigure/security/AuthenticationManagerConfiguration.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [org.springframework.boot.autoconfigure.security.SecurityProperties]: : Error creating bean with name 'securityProperties': Could not bind properties to [unknown] (target=security, ignoreInvalidFields=false, ignoreUnknownFields=false, ignoreNestedProperties=false); nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'token[key]' of bean class [org.springframework.boot.autoconfigure.security.SecurityProperties]: Cannot access indexed value in property referenced in indexed property path 'token[key]'; nested exception is org.springframework.beans.NotReadablePropertyException: Invalid property 'token[key]' of bean class [org.springframework.boot.autoconfigure.security.SecurityProperties]: Bean property 'token[key]' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityProperties': Could not bind properties to [unknown] (target=security, ignoreInvalidFields=false, ignoreUnknownFields=false, ignoreNestedProperties=false); nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'token[key]' of bean class [org.springframework.boot.autoconfigure.security.SecurityProperties]: Cannot access indexed value in property referenced in indexed property path 'token[key]'; nested exception is org.springframework.beans.NotReadablePropertyException: Invalid property 'token[key]' of bean class [org.springframework.boot.autoconfigure.security.SecurityProperties]: Bean property 'token[key]' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
this is my application class:
#ComponentScan (basePackages = { "com.test" })
#EnableAutoConfiguration(exclude = {MetricFilterAutoConfiguration.class, MetricRepositoryAutoConfiguration.class})
#Domain(basePackages = { "com.test.domain" })
public class Application {
private final Logger log = LoggerFactory.getLogger(Application.class);
#Inject
private Environment env;
#PostConstruct
public void initApplication() throws IOException {
if (env.getActiveProfiles().length == 0) {
log.warn("No Spring profile configured, running with default configuration");
} else {
log.info("Running with Spring profile(s) : {}", Arrays.toString(env.getActiveProfiles()));
}
}
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Application.class);
app.setShowBanner(false);
SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args);
// Check if the selected profile has been set as argument.
// if not the development profile will be added
addDefaultProfile(app, source);
}
/**
* Set a default profile if it has not been set
*
* #param app
* #param source
*/
private static void addDefaultProfile(SpringApplication app, SimpleCommandLinePropertySource source) {
if (!source.containsProperty("spring.profiles.active")) {
app.setAdditionalProfiles(Constants.SPRING_PROFILE_DEVELOPMENT);
}
}
/**
*
* #return
*/
#Bean
public HttpMessageConverter<String> responseBodyConverter() {
return new StringHttpMessageConverter(Charset.forName("UTF-8"));
}
#Bean
public Filter characterEncodingFilter() {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
return characterEncodingFilter;
}
/**
*
* #return
*/
#Bean
public BeanNameAutoProxyCreator lazyInitAutoProxyCreator() {
BeanNameAutoProxyCreator autoProxyCreator = new BeanNameAutoProxyCreator();
TargetSourceCreator[] targetSourceCreators = {lazyInitTargetSourceCreator()};
autoProxyCreator.setCustomTargetSourceCreators(targetSourceCreators);
return autoProxyCreator;
}
#Bean
public LazyInitTargetSourceCreator lazyInitTargetSourceCreator() {
return new LazyInitTargetSourceCreator();
}
}
Try to add the #Configuration annotation to your Application class
#Configuration
#ComponentScan (basePackages = { "com.test" })
#EnableAutoConfiguration(exclude = {MetricFilterAutoConfiguration.class, MetricRepositoryAutoConfiguration.class})
#Domain(basePackages = { "com.test.domain" })
public class Application {
//some code
}