Error while starting state machine - spring-statemachine

while calling statemachine.start() Iam always getting the below stack trace.But it's not stopping my state machine execution though, since Iam not using any annotation for state transitions, state entry etc.
Please help me in fixing this error.
19:41:56.515 ERROR o.s.s.s.StateMachineObjectSupport - Unable to initialize annotation handlers
java.lang.IllegalStateException: Bean factory must be instance of ListableBeanFactory, was null
at org.springframework.util.Assert.state(Assert.java:392) ~[spring-core-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.statemachine.processor.StateMachineHandlerCallHelper.setBeanFactory(StateMachineHandlerCallHelper.java:93) ~[spring-statemachine-core-1.1.1.BUILD-SNAPSHOT.jar:1.1.1.BUILD-SNAPSHOT]
at org.springframework.statemachine.support.StateMachineObjectSupport.doStart(StateMachineObjectSupport.java:66) ~[spring-statemachine-core-1.1.1.BUILD-SNAPSHOT.jar:1.1.1.BUILD-SNAPSHOT]
at org.springframework.statemachine.support.AbstractStateMachine.doStart(AbstractStateMachine.java:317) [spring-statemachine-core-1.1.1.BUILD-SNAPSHOT.jar:1.1.1.BUILD-SNAPSHOT]
at org.springframework.statemachine.support.LifecycleObjectSupport.start(LifecycleObjectSupport.java:120) [spring-statemachine-core-1.1.1.BUILD-SNAPSHOT.jar:1.1.1.BUILD-SNAPSHOT]
at org.tiaa.devops.process.delegate.StateMachineDelegateImpl.execute(StateMachineDelegateImpl.java:103) [classes/:na]
at org.tiaa.devops.process.delegate.StateMachineDelegateImpl.executePipeline(StateMachineDelegateImpl.java:67) [classes/:na]
at org.tiaa.devops.process.delegate.StateMachineDelegateImpl.lambda$0(StateMachineDelegateImpl.java:59) [classes/:na]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[na:1.8.0_66]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) ~[na:1.8.0_66]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) ~[na:1.8.0_66]
at java.lang.Thread.run(Thread.java:745) ~[na:1.8.0_66]

Managed to get a solution for this.
I autowired the the Spring application context into my class. I then extracted the AutowireCapableBeanFactory from this and set this up inside the builder. As follows:
#Autowired
private ApplicationContext appContext;
private void buildStateMachine() throws Exception {
Builder<EnquiryStatus, Event> builder = StateMachineBuilder.builder();
builder.configureConfiguration().withConfiguration().beanFactory(appContext.getAutowireCapableBeanFactory());
}
(copied verbatim from https://stackoverflow.com/a/37926670/122441 )

Related

Spring is failling to Autowire Azure Storage Blob

I have a Spring Batch that has a writer to an Azure Storage Blob.
I am using this Azure/Spring Dependency:
azure-spring-boot-starter-storage 3.4.0
On my application properties I have:
azure.storage.accountName=myAccount
azure.storage.accountKey=myKey
Then inside my BatchConfig class I autowired the AZ Storage:
#Autowired
private BlobServiceClientBuilder blobServiceClientBuilder;
private final BlobServiceAsyncClient blobServiceAsyncClient = blobServiceClientBuilder.buildAsyncClient();
Now when I start my application, I am getting a NullPointerException because the BlobServiceClientBuilder cannot be instantiated.
Caused by: java.lang.NullPointerException: null
at com.example.dbreader.configuration.BatchConfig.<init>(BatchConfig.java:55) ~[classes/:na]
at com.example.dbreader.configuration.BatchConfig$$EnhancerBySpringCGLIB$$58787751.<init>(<generated>) ~[classes/:na]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_221]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_221]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_221]
at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_221]
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:212) ~[spring-beans-5.3.5.jar:5.3.5]
What am I doing wrong when autowiring the Azure Blob Bean?
One more thing I am using the Spring Resource to instantiate a blob file:
#Value("blob://{containerName}/" + "#{stepExecutionContext['marketName']}")
private Resource blobFile;
Encountered the same issue . Looks like its a mistake from documentation.
Azure.storage.blob-endpoint property is mandatory for blobClient and optional for fileClient. Add
Azure.storage.blob-endpoint= https://<account-name>.blob.core.windows.net
to resolve the issue
I encountered the same issue. finally I found that the buildClient() method couldn't be put in global or constructor. just put it in the GET/POST method, it'll work. FYR.
#Autowired
private BlobServiceClientBuilder blobServiceClientBuilder;
private BlobServiceClient blobServiceClient;
#GetMapping
public String readBlobFile() throws IOException {
blobServiceClient = blobServiceClientBuilder.buildClient();
AzureStorageResourcePatternResolver storageResourcePatternResolver = new AzureStorageResourcePatternResolver(blobServiceClient);

spring boot data cassandra reactive JmxReporter problem

I updated my project to spring-boot Version 2.1.0.RELEASE.
Now i get the following error:
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.cassandra.ReactiveSession]: Factory method 'reactiveSession' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'session' defined in class path resource [ch/sbb/kat/fc/config/CassandraConfig.class]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: com/codahale/metrics/JmxReporter
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
at org.springframework.beans.factory.support.ConstructorResolver.lambda$instantiate$2(ConstructorResolver.java:615)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:614)
... 120 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'session' defined in class path resource [ch/sbb/kat/fc/config/CassandraConfig.class]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: com/codahale/metrics/JmxReporter
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1745)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:576)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:339)
at ch.sbb.kat.fc.config.CassandraConfig$$EnhancerBySpringCGLIB$$a22674d7.session(<generated>)
at org.springframework.data.cassandra.config.AbstractCassandraConfiguration.getRequiredSession(AbstractCassandraConfiguration.java:66)
at org.springframework.data.cassandra.config.AbstractReactiveCassandraConfiguration.reactiveSession(AbstractReactiveCassandraConfiguration.java:47)
at ch.sbb.kat.fc.config.CassandraConfig$$EnhancerBySpringCGLIB$$a22674d7.CGLIB$reactiveSession$7(<generated>)
at ch.sbb.kat.fc.config.CassandraConfig$$EnhancerBySpringCGLIB$$a22674d7$$FastClassBySpringCGLIB$$7973a63.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
at ch.sbb.kat.fc.config.CassandraConfig$$EnhancerBySpringCGLIB$$a22674d7.reactiveSession(<generated>)
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:498)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
... 123 more
Caused by: java.lang.NoClassDefFoundError: com/codahale/metrics/JmxReporter
at com.datastax.driver.core.Metrics.<init>(Metrics.java:146)
at com.datastax.driver.core.Cluster$Manager.init(Cluster.java:1501)
at com.datastax.driver.core.Cluster.init(Cluster.java:208)
at com.datastax.driver.core.Cluster.connectAsync(Cluster.java:376)
at com.datastax.driver.core.Cluster.connect(Cluster.java:332)
at org.springframework.data.cassandra.config.CassandraCqlSessionFactoryBean.connect(CassandraCqlSessionFactoryBean.java:89)
at org.springframework.data.cassandra.config.CassandraCqlSessionFactoryBean.afterPropertiesSet(CassandraCqlSessionFactoryBean.java:82)
at org.springframework.data.cassandra.config.CassandraSessionFactoryBean.afterPropertiesSet(CassandraSessionFactoryBean.java:59)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.lambda$invokeInitMethods$5(AbstractAutowireCapableBeanFactory.java:1795)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1794)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1741)
... 143 more
Caused by: java.lang.ClassNotFoundException: com.codahale.metrics.JmxReporter
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 155 more
Using the property introduced in this issue https://github.com/spring-projects/spring-boot/issues/14778 seems to have no effect to solve my issue.
How can i disable jmx for cassandra?
My current cassandra config looks like this:
#Configuration
#EnableReactiveCassandraRepositories({"repository"})
public class CassandraConfig extends AbstractReactiveCassandraConfiguration {
#Value("${cassandra.host}")
private String host;
#Override
protected String getKeyspaceName() {
return "keyspace";
}
#Override
public String[] getEntityBasePackages() {
return new String[]{"model"};
}
#Override
public SchemaAction getSchemaAction() {
return SchemaAction.CREATE_IF_NOT_EXISTS;
}
#Override
public String getContactPoints() {
return host;
}
}
The spring.data.cassandra.jmx-enabled property is used when Spring Boot is auto-configuring a Cassandra Cluster bean. By extending AbstractReactiveCassandraConfiguration, you are switching off this auto-configuration in favour of the Cluster bean that's created by AbstractClusterConfiguration which is a super-class of AbstractReactiveCassandraConfiguration. As a result, the property has no effect.
There are two ways that you can fix your problem:
Remove your AbstractReactiveCassandraConfiguration sub-class and use the various spring.data.cassandra.* properties to configure things instead.
Override cluster on AbstractClusterConfiguration in CassandraConfig, call super.cluster() to get the CassandraClusterFactoryBean and then call setJmxReportingEnabled(false) on the factory bean before returning it.
Alternatively, if you are not using Dropwizard elsewhere in your application, you may be able to downgrade to an older version that is compatible with Cassandra's JMX reporting by overriding the dropwizard-metrics.version property in your pom.xml or build.gradle.
instead of overriding cluster as mentionned by Andy Wilkinson, you could alternatively override getMetricsEnabled so that always returns false.
#Override
protected boolean getMetricsEnabled() { return false; }
I tried the the answers here, I don't know how but error still persisted.
I read this from docs.datastax.com , where they talked about Moving JMX reporting in Metrics 4 to a separate module, metrics-jmx. Which they made clear that it might cause issues/errors.
To fix this, I just had to call this method .withoutJMXReporting() as in the below.
Cluster cluster = Cluster.builder()
.withoutJMXReporting()
.build();
You can follow quietly here
Including old version of library also fixes problem:
implementation("io.dropwizard.metrics:metrics-core:3.2.2")
#Bean
public CassandraClusterFactoryBean cluster() {
CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();
cluster.setContactPoints(environment.getProperty("spring.data.cassandra.contact-points"));
cluster.setPort(Integer.parseInt(environment.getProperty("spring.data.cassandra.port")));
cluster.setJmxReportingEnabled(false);
return cluster;
}
cluster.setJmxReportingEnabled(false) is the answer seems.

Error creating bean with name 'scopedTarget.userPlatform': Scope 'user' is not active for the current thread

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.userPlatform': Scope 'user' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: Not within any context!
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:355)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:35)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.getTarget(CglibAopProxy.java:705)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
at com.cumulocity.sdk.client.PlatformImpl$$EnhancerBySpringCGLIB$$998b9bde.close()
at com.test.CleanAssignedSoftwareService.CreateSoftwareAssignmentOperations(CleanAssignedSoftwareService.java:235)
at com.test.ScheduledTask.reportCurrentTime(ScheduledTask.java:33)
at sun.reflect.GeneratedMethodAccessor69.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:65)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)
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)
Caused by: java.lang.IllegalStateException: Not within any context!
at com.cumulocity.microservice.context.ContextServiceImpl.getContext(ContextServiceImpl.java:41)
at com.cumulocity.microservice.context.annotation.EnableContextSupportConfiguration$2.getContextId(EnableContextSupportConfiguration.java:45)
at com.cumulocity.microservice.context.scope.BaseScope.doGetSynchronized(BaseScope.java:47)
at com.cumulocity.microservice.context.scope.BaseScope.get(BaseScope.java:39)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:340)
... 19 common frames omitted
When running some code with the #Scheduled Annotation you need to define the context. Otherwise you get this exception, as the thread using a cumulocity API is not within any context.
E.g. for all subscribed tenants:
private final MicroserviceSubscriptionsService subscriptions;
#Scheduled(fixedDelay = 5 * 60 * 1000)
private void checkForAgentRepresentation() {
for (final MicroserviceCredentials mc : subscriptions.getAll()) {
final String tenant = mc.getTenant();
subscriptions.runForTenant(tenant, () -> {
//doSomething like
inventoryApi.get(...);
});
}
}

Getting "Scope 'step' is not active for the current thread" while creating spring batch beans

In my Spring batch configuration, I'm trying to setup a partitioned step, which accesses values from JobParameters as follows :
#Bean
#Qualifier("partitionJob")
public Job partitionJob() throws Exception {
return jobBuilderFactory
.get("partitionJob")
.incrementer(new RunIdIncrementer())
.start(partitionStep(null))
.build();
}
#Bean
#StepScope //I'm getting exception here - > Error creating bean
public Step partitionStep(
#Value("#{jobParameters[gridSize]}") String gridSize)
throws Exception {
return stepBuilderFactory
.get("partitionStep")
.partitioner("slaveStep", partitioner())
.gridSize(
StringUtils.isEmpty(gridSize) ? 10 : Integer
.parseInt(gridSize))
.step(slaveStep(50000))
.taskExecutor(threadPoolTaskExecutor()).build();
}
#Bean
#StepScope
public Step slaveStep(int chunkSize) throws Exception {
return stepBuilderFactory
.get("slaveStep")
.<Person,Person> chunk(chunkSize)
.reader(jdbcPagingItemReader()),
.writer(csvFileWriterParts())
.listener(stepExecutionListener()).build();
}
I have added #EnableBatchProcessing annotation to my SpringBoot application.
Since I wanted to access JobParameters while constructing a step, I used #StepScope. I have an example that works fine, without #StepScope annotation, but in that case I'm not accessing any JobParameters or anything from context.
But If I use StepScope annotation on partitionStep, I'm getting
Error creating bean with name 'scopedTarget.partitionStep': Scope
'step' is not active for the current thread; consider defining a
scoped proxy for this bean if you intend to refer to it from a
singleton; nested exception is java.lang.IllegalStateException: No
context holder available for step scope
but If I change it to JobScope, then it is failing at slaveStep() with same error message.
What is the correct scope to be used in such cases and how to resolve this issue I'm getting ?
What is the better way of accessing JobParameters while configuring spring beans ?
Exception stack is as below
2018-05-25 21:07:32,075 ERROR [main]
org.springframework.batch.core.job.AbstractJob : Encountered fatal
error executing job
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'scopedTarget.partitionStep': Scope 'step' is
not active for the current thread; consider defining a scoped proxy
for this bean if you intend to refer to it from a singleton; nested
exception is java.lang.IllegalStateException: No context holder
available for step scope at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:361)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at
org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:35)
at
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:192)
at com.sun.proxy.$Proxy55.getName(Unknown Source) at
org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:115)
at
org.springframework.batch.core.job.AbstractJob.handleStep(AbstractJob.java:392)
at
org.springframework.batch.core.job.SimpleJob.doExecute(SimpleJob.java:135)
at
org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:306)
at
org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:135)
at
org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50)
at
org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:128)
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:498) at
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at
org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy54.run(Unknown Source) at
com.sample.main(ExtractApplication.java:58)
Caused by: java.lang.IllegalStateException: No context holder
available for step scope at
org.springframework.batch.core.scope.StepScope.getContext(StepScope.java:167)
at
org.springframework.batch.core.scope.StepScope.get(StepScope.java:99)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:346)
... 23 common frames omitted
If I modify to JobScope, I get exception on slaveStep, which is similar to the above exception.
Please try the option Spring batch scope issue while using spring boot, posted by Manh. I guess it solved the problem. Unfortunately I no longer have access to the code base, to confirm what I did for the fix.

Spring Security Java Config

I'm trying to use JavaConfig instead of XML configuration for Spring Security.
I would like to use #PreAuthorization for declaring access rights.
My Spring Security Config looks like this:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity( prePostEnabled = true )
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void registerAuthentication( AuthenticationManagerBuilder auth ) throws Exception {
auth
.inMemoryAuthentication()
.withUser( "user" ).password( "password" ).roles( "USER" );
}
}
However, this doesn't work. Once I deploy my web application I receive an error Error creating bean with name 'methodSecurityInterceptor' defined in class path resource.
After some research I found out that I have to add the aopalliance library to my project. Unfortunately that didn't resolved my problem.
Here is the complete stack trace:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'methodSecurityInterceptor' defined in class path resource [org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.aopalliance.intercept.MethodInterceptor org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration.methodSecurityInterceptor() throws java.lang.Exception] threw exception; nested exception is java.lang.IllegalArgumentException: Expecting to only find a single bean for type interface org.springframework.security.authentication.AuthenticationManager, but found []
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:592)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1094)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:989)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:381)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:293)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4937)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1558)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:301)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:620)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:567)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:301)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1487)
at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:97)
at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1328)
at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1420)
at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:848)
at sun.reflect.GeneratedMethodAccessor42.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:322)
at sun.rmi.transport.Transport$1.run(Transport.java:177)
at sun.rmi.transport.Transport$1.run(Transport.java:174)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:173)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:556)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:811)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:670)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.aopalliance.intercept.MethodInterceptor org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration.methodSecurityInterceptor() throws java.lang.Exception] threw exception; nested exception is java.lang.IllegalArgumentException: Expecting to only find a single bean for type interface org.springframework.security.authentication.AuthenticationManager, but found []
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:581)
... 56 more
Caused by: java.lang.IllegalArgumentException: Expecting to only find a single bean for type interface org.springframework.security.authentication.AuthenticationManager, but found []
at org.springframework.util.Assert.isTrue(Assert.java:65)
at org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration.lazyBean(GlobalMethodSecurityConfiguration.java:352)
at org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration.authenticationManager(GlobalMethodSecurityConfiguration.java:240)
at org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration.methodSecurityInterceptor(GlobalMethodSecurityConfiguration.java:116)
at org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration$$EnhancerByCGLIB$$890899ea.CGLIB$methodSecurityInterceptor$2(<generated>)
at org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration$$EnhancerByCGLIB$$890899ea$$FastClassByCGLIB$$fba343c4.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:326)
at org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration$$EnhancerByCGLIB$$890899ea.methodSecurityInterceptor(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
... 57 more
According to your stacktrace, there’s no AuthenticationManager bean in your context.
Expecting to only find a single bean for type interface org.springframework.security.authentication.AuthenticationManager, but found []
It seems that you need to explicitly expose AuthenticationManager as a bean; try this:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser( "user" ).password( "password" ).roles( "USER" );
}
#Bean #Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
from the stacktrace, you don't have authentication manager defiend correctly :
Caused by: java.lang.IllegalArgumentException: Expecting to only find a single bean for type interface org.springframework.security.authentication.AuthenticationManager, but found []
Here is working example :
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
Just add the global method annotation, and change to method to not override and be autowired.
As NimChimpsky notes, Spring 3.2.0.RELEASE requires a configuration update.
Using this configuration, I was getting exactly the same exception as the OP, but only about half the time. The other half of the time the app started up just fine. I assume that there's some kind of race condition.
Originally I was pulling the security configuration in using #Import on my root configuration:
#Configuration
#Import(SecurityConfig.class)
... other annotations ...
public class RootConfig {
...
}
When I replaced that with
public class WebAppInit extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { RootConfig.class, SecurityConfig.class };
}
}
the problem went away. Didn't dive into the reasons why, so I can't speak to that, but you might give it a try.
In my case, I have a line super.configure(auth); in the overriding method configure(AuthenticationManagerBuilder auth).
After it was removed, the exception is gone.

Resources