@Autowired不在Spring Security工作

问题描述 投票:1回答:3

我在我的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>

我究竟做错了什么?

java spring spring-mvc spring-security autowired
3个回答
1
投票

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

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

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


0
投票

我不是100%肯定,但看起来问题是你正在尝试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


0
投票

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

user service imp了.Java

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

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

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

Web MVC config.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

© www.soinside.com 2019 - 2024. All rights reserved.