如何在java类中创建Spring Security 3.1 Datasource bean

时间:2015-04-24 17:19:27

标签: java spring spring-security spring-bean

我是JSF和Spring Security的新手。 我正在构建一个基于this tutorial的JSF 2项目。我想将dataSource bean放在java类中,因为我正在生成JDBC连接的url和另一个类中的用户。 如何将我的security-config.xml中的代码放到java类中。

 <beans:bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <beans:property name="url" value="jdbc:mysql://localhost:3306/spring_security_db" />
    <beans:property name="username" value="root" />
    <beans:property name="password" value="" />
 </beans:bean>

2 个答案:

答案 0 :(得分:1)

一种解决方案是使用Spring expression language。您可以指定要检索的方法调用,例如url参数:

<beans:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <beans:property name="url" value="#{someOtherBean.someMethod()}" />
    <beans:property name="username" value="root" />
    <beans:property name="password" value="" />
</beans:bean>

您需要定义您正在引用其方法的另一个bean。程序化方法将是这样的:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

@Configuration
public class AppConfig {

    @Bean
    public DriverManagerDataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();

        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/spring_security_db");
        dataSource.setUsername("root");
        dataSource.setPassword("");

        return dataSource;
    }
}

在Spring配置中,您需要使用适当的包指定组件扫描以获取bean:

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

    <context:component-scan base-package="yourpackage.configpackage"/>          

</beans>

答案 1 :(得分:1)

你应该创建一个实现DriverManagerDataSource的新类,它是构造函数,然后在你的bean定义中,在class标签中放置该类的名称。 你的班级是这样的:

package dao; 
public class dataSource extends DriverManagerDataSource { 
 public dataSource() { 
 // TODO Auto-generated constructor stub 
  this.setDriverClassName("com.mysql.jdbc.Driver"); 
  this.setUrl("jdbc:mysql://.../....."); 
  this.setUsername(""); this.setPassword(""); 
   }
}

你的bean定义如下:

<beans:bean id="dataSource" class="dao.dataSource">
相关问题