@Autowired不在Spring Security工作

时间:2014-02-19 01:53:31

标签: java spring spring-mvc spring-security autowired

我在我的Spring Web MVC项目中使用Java配置实现Spring Security,并且由于某种原因,@Autowired注释不是在我的安全配置类中注入字段。我在SO上发现了this非常相似的问题,但我的设置很多更简单,并且在我的情况下,接受的答案根本不适用。

作为参考,我遵循了Spring自己的安全文档(here)的前三章,并且内存中的身份验证工作非常快。然后,我想切换到JDBC身份验证,并使用DataSource注释注入@Autowired(如this example所示)。但是,我收到了这个错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource com.tyedart.web.config.security.SecurityConfig.dataSource; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] 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)}

这是我的安全配置类。正如您所看到的,我通过明确查找我的数据源解决了这个问题:

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

//  @Autowired
//  private DataSource dataSource;

//  @Autowired
//  public PasswordEncoder passwordEncoder;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

        InitialContext ctx = new InitialContext();
        DataSource dataSource = (DataSource) ctx.lookup("java:/comp/env/jdbc/TyedArtDB");

        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

        auth
            .jdbcAuthentication()
                .dataSource(dataSource)
                .passwordEncoder(passwordEncoder);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/manage/**").hasRole("ADMIN")
                .and()  
            .formLogin();
    }
}

这是我非常简单的root-context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd">

       <!-- Root Context: defines shared resources visible to all other web components -->

       <jee:jndi-lookup id="dataSource" jndi-name="jdbc/TyedArtDB"/>

       <bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>

</beans>

我做错了什么?

3 个答案:

答案 0 :(得分:1)

在root-context.xml中添加<context:component-scan base-package="your.package.where.your.bean.is"/>

您可以取消注释@Autowired in字段声明并将其从约束器中删除。您可以找到更多信息here

如果您@Autowired是一个bean,请不要忘记使用new删除初始化。

答案 1 :(得分:0)

我不是百分百肯定,但看起来问题是你正在尝试Autowire DataSource,它实际上并没有被定义为Spring bean:

<jee:jndi-lookup id="dataSource" jndi-name="jdbc/TyedArtDB"/>

创建一个可以在XML中引用的对象,但是不认为它实际上创建了一个bean? (可能是错的,春天的JNDI查找并没有那么多。)

是否可以切换到纯java配置并删除XML引用?

@Bean
public DataSource dataSource() throws Exception {
    Context ctx = new InitialContext();
    return (DataSource) ctx.lookup("jdbc/TyedArtDB");
}

(取自这个答案:https://stackoverflow.com/a/15440797/258813

你可以像这样移动密码编码器:

@Bean public BCryptPasswordEncoder bCryptPasswordEncoder(){
    return new BCryptPasswordEncoder();
}

取自:http://automateddeveloper.blogspot.co.uk/2014/02/spring-4-xml-to-annotation-configuration.html

答案 2 :(得分:0)

这是我用来自动装配BCryptPasswordEncoder的一个例子:

<强> UserServiceImpl.java

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public User findUserByEmail(String email) {
        return null;
    }
}

<强> WebMvcConfig.java

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        return bCryptPasswordEncoder;
    }
}

如果您注意到,WebMvcConfig.java在passwordEncoder()方法之前就有@Bean注释。它表明一个方法生成一个由Spring容器管理的bean。

https://docs.spring.io/autorepo/docs/spring/4.2.4.RELEASE/javadoc-api/org/springframework/context/annotation/Bean.html