Spring Security配置自动装配自定义UserDetailsS​​ervice bean

时间:2016-02-20 16:26:35

标签: spring spring-security autowired

我最近回到了一个我正在研究的S​​pring项目,并且在启动应用程序时遇到了问题。这个问题可能是重复的,但我找不到答案。

这是我最初的SecurityConfig.java的片段:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired private UserService userService;

    /**
     * Global security config to set the user details service etc.
     * @param auth authentication manager
     * @throws Exception
     */
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(userService)
                .passwordEncoder(passwordEncoder());
    }

UserService对象实现UserDetailsS​​ervice。这在启动时出错:

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.clubmate.web.service.UserService com.clubmate.web.config.SecurityConfig.userService; nested exception is java.lang.IllegalArgumentException: Can not set com.clubmate.web.service.UserService field com.clubmate.web.config.SecurityConfig.userService to com.sun.proxy.$Proxy62
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    ... 58 more
Caused by: java.lang.IllegalArgumentException: Can not set com.clubmate.web.service.UserService field com.clubmate.web.config.SecurityConfig.userService to com.sun.proxy.$Proxy62
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
    at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:81)
    at java.lang.reflect.Field.set(Field.java:764)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:569)
    ... 60 more

从我的阅读中,这是因为我正在自动装配一个具体的类而不是UserDetailsS​​ervice接口,但这对我来说很奇怪,因为当我之前处理这个项目时,自动装配具体的类工作正常。

我放弃了,只是将其更改为自动装载SecurityConfig.java中的UserDetailsS​​ervice接口。

我不确定这是否相关,但是现在在启动时我得到以下错误,对于@Service的任何其他bean对象(@Autowire private UserService userService等)。

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.clubmate.web.service.UserService com.clubmate.web.service.PageService.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.clubmate.web.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    ... 58 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.clubmate.web.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545)
    ... 60 more

任何帮助非常感谢。这让我疯了好几个小时。

更新

更多信息:我有另一个配置类(AppConfig.java),其中包含以下内容:

@Configuration
@EnableWebMvc
@ComponentScan("com.clubmate.web")
@PropertySource(value = { "classpath:application.properties" })
@Import({
        SecurityConfig.class,
        CacheConfig.class,
        DatabaseConfig.class,
        CronConfig.class
})
public class AppConfig extends WebMvcConfigurerAdapter {
    // ...
}

我还有两个app初始化程序类,一个用于MVC,即:

public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    public Class<?>[] getRootConfigClasses() {
        return new Class[] {
                AppConfig.class
        };
    }

    @Override
    public Class<?>[] getServletConfigClasses() {
        return new Class[] {
                StartupHousekeeping.class,
                ShutdownHousekeeping.class
        };
    }

    @Override
    public String[] getServletMappings() {
        return new String[] {
                "/"
        };
    }

}

......和安全的另一个是:

public class AppInitializer extends AbstractSecurityWebApplicationInitializer {

    private static Logger log = LogManager.getLogger(AppInitializer.class);

    @Override
    protected void beforeSpringSecurityFilterChain(ServletContext context) {
        // load multipart filter before other filters are created
        // see: http://docs.spring.io/spring-security/site/docs/4.0.1.RELEASE/reference/htmlsingle/#csrf-multipart
        MultipartFilter multipartFilter = new MultipartFilter();
        multipartFilter.setMultipartResolverBeanName("multipartResolver");
        insertFilters(context, multipartFilter);
    }

}

这些是否会以某种方式发生冲突?

更新2

抛出异常的屏幕截图:http://i.imgur.com/r6AsOob.jpg

var1是SecurityConfig类,var2是一个Proxy对象,应该是我的UserService类。

1 个答案:

答案 0 :(得分:5)

自动装配失败,因为默认情况下,Spring使用JDK动态代理(通过实现其接口来代理目标类)来创建代理。 另一方面,基于CGLIB的代理是目标类的子类。

请参阅:What is the difference between JDK dynamic proxy and CGLib?

要启用基于CGLIB的代理,请使用@Configuration为您的@EnableAspectJAutoProxy(proxyTargetClass=true)个班级添加注释:

@Configuration
@EnableAspectJAutoProxy(proxyTargetClass=true)
public class AppConfig {
    ...
}
  

请注意,从版本3.2开始,CGLIB被重新打包并包含在spring-core JAR中。因此,它可以直接使用。