【发布时间】:2015-09-29 13:02:43
【问题描述】:
我正在使用 Spring Security 4,我想通过查询数据库进行身份验证。我创建了用户和权限表。我的数据源的 jdbc 连接 bean 是使用注释在 java 文件中定义的。我的 spring 安全配置在 xml 中。我已经读到正在使用相同的 contextLoader,因此加载所有 bean 应该没有问题。但是,如何将 java 文件中定义的 dataSource bean 导入到我的 spring 安全配置文件中?
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
@Configuration
@MapperScan("com.iz.acsadmin.dao")
public class DataConfig{
@Bean(name = "dataSource" )
public DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUrl("jdbc:postgresql://192.168.1.3:5432/Student");
dataSource.setUsername("postgres");
dataSource.setPassword("admin");
return dataSource;
}
...
XML Spring-Config 文件
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/" access="permitAll" />
<intercept-url pattern="/test.htm" access="hasRole('USER') or hasRole('ADMIN') or hasRole('DBA')" />
<intercept-url pattern="/welcome.htm" access="hasRole('USER') or hasRole('ADMIN') or hasRole('DBA')" />
<form-login />
</http>
<authentication-manager >
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query=
"SELECT USERNAME, PASSWORD, ENABLED FROM USERS WHERE USERNAME=?"
authorities-by-username-query=
"SELECT USERNAME, AUTHORITY FROM AUTHORITIES WHERE USERNAME=?"
/>
</authentication-provider>
</authentication-manager>
</beans:beans>
xml文件中的dataSource bean在java文件中找不到主dataSource bean。
【问题讨论】:
-
您能否发布您的代码以听取或向我们展示更多详细信息?
-
对不起,我是新来的。我应该再放一些文件吗?
标签: spring spring-mvc spring-security