簡體   English   中英

@Autowired在Spring Security中不起作用

[英]@Autowired not working in Spring Security

我正在Spring Web MVC項目中使用Java配置來實現Spring Security,由於某種原因,@ @Autowired注釋未在我的安全配置類中注入字段。 我在SO上發現了一個非常相似的問題,但我的設置簡單得多,並且可接受的答案根本不適用於我的情況。

作為參考,我遵循了Spring自己的安全性文檔的前三章( 在此處 ),並使內存內身份驗證工作很快。 然后,我想切換到JDBC身份驗證,並注入帶有@Autowired批注的DataSource (如本示例所示)。 但是,我收到此錯誤:

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>

我究竟做錯了什么?

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

您可以在字段聲明中取消注釋@Autowired並將其從承包商中刪除。 您可以在這里找到更多信息

如果@Autowired一個bean,請不要忘記使用new刪除初始化。

我不確定100%,但是看來問題出在您要嘗試自動裝配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

這是我用來自動連接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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM