Spring引导-如何避免在Spring引导类中使用新的注释为组件


@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声明:

@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);
}

从上面的代码片段可以看出:

return new CustomProviderManager(listOfProviders);

产生以下错误:

org.springframework.beans.factory.UnsatisfiedDependencyException:创建文件[/opt/hsd/tomcat-9.0.43/webapp/csesonlinepp/WEB-INF/classes.gov/nm/cses/gen/customProviderManager.class]中定义的名称为"customProviderManager"的bean时出错:通过构造函数参数0表示的不满足依赖关系;嵌套异常为org.springframework.beans.factory.BeanCreationException:创建文件[/opt/hsd/tomcat-9.0.43/webapps/cesonlinepp/WEB-INF/classes.gov/nm/cses/gen/springSecurityConfig.class]中定义的名称为"springSecurityConfig"的bean时出错:合并bean定义的后处理失败;嵌套异常为java.lang.IllegalStateException:未能从ClassLoader〔ParallelWebappClassLoader ^M中内省Class〔gov.nm.cses.gen.SpringSecurityConfig〕上下文:csesonlineapp^M委托:false ^M---------->父类加载器:^Mjava.net.URLClassLoader@38bc8ab5

我认为这是由于当类被注释为Component时使用了new运算符而不是Autowiring。如果我错了,请纠正我。

在上述情况下,我如何避免使用new

为什么希望类CustomProviderManager使用@component作为组件?

只要从类中删除@Component,问题就会消失。

如果你想要自动布线AuthenticationManager,只需在SpringSecurityConfig类中进行自动布线

最新更新