【发布时间】:2014-02-19 01:53:30
【问题描述】:
我在我的 Spring Web MVC 项目中使用 Java 配置实现 Spring Security,由于某种原因,@Autowired 注释没有在我的安全配置类中注入字段。我在 SO 上发现了 this 非常相似的问题,但是我的设置要简单得多,并且接受的答案在我的情况下根本不适用。
作为参考,我遵循了 Spring 自己的安全文档 (here) 的前三章,并且很快就获得了内存身份验证。然后我想切换到 JDBC 身份验证并注入带有@Autowired 注释的DataSource(如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