Spring boot - How to avoid using new in Spring boot class annotated as component

Viewed 54
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        listOfProviders.add(racfAuthenticationProvider);
        listOfProviders.add(ldapAuthenticationProvider());
        return new CustomProviderManager(listOfProviders); // <- have a look here
    }
}

CustomProviderManager declaration:

@Component
public class CustomProviderManager extends ProviderManager {

private AuthenticationEventPublisher eventPublisher = new NullEventPublisher();
private AuthenticationManager parent;
private boolean eraseCredentialsAfterAuthentication = true;

public CustomProviderManager(List<AuthenticationProvider> providers) {
    super(providers);
}

As can be seen from the code snippet above:

return new CustomProviderManager(listOfProviders);

Produces the following error:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customProviderManager' defined in file [/opt/hsd/tomcat-9.0.43/webapps/csesonlineapp/WEB-INF/classes/gov/nm/cses/gen/CustomProviderManager.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityConfig' defined in file [/opt/hsd/tomcat-9.0.43/webapps/csesonlineapp/WEB-INF/classes/gov/nm/cses/gen/SpringSecurityConfig.class]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [gov.nm.cses.gen.SpringSecurityConfig] from ClassLoader [ParallelWebappClassLoader^M context: csesonlineapp^M delegate: false^M ----------> Parent Classloader:^M java.net.URLClassLoader@38bc8ab5

I believe this is happening due to a new operator instead of Autowiring when classes are annotated as Component. Please correct me if I am wrong.

How can I avoid using new in the above case?

1 Answers

Why do you want the class CustomProviderManager to be component - using @Component?

Just remove @Component from the class, the problem will be gone.

If you want autowire AuthenticationManager, just autowire in SpringSecurityConfig class

Related