数据库在Spring中配置

  1. applicationContext.xml中,以Bean的形式出现,因为其也是一种资源

    
    
    
    

  1. 将资源与bean的配置分开,eg.datasourse
    资源信息放入jdbc.properties文件,xml或JdbcConfig中通过${...}获取
jdbc.properties

jdbc.diverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/xxx
jdbc.user=root
jdbc.password=root

    


    
    
    
    

public class JdbcConfig{
    @Value(${jdbc.diverClass})
    private String diverClass;
    
    @Value(${jdbc.jdbcUrl})
    private String jdbcUrl
    
    @Value(${jdbc.user})
    private String user
    
    @Value(${jdbc.password})
    private String password
    
    @Bean(name="runner")
    puclic QueryRunner getQueryRunner(@Qualifier("dataSource") DataSource ds){
        return new QueryRunner(ds)
    }
    
    @Bean(name="dataSource")
    public DataSource getDataSource(){
    ComboPooledDataSource dataSource = new ComboPooledDataSource();
    
    dataSource.setDriverClass(driverClass);
    dataSource.setJdbcUrl(url);
    dataSource.setUser(user);
    dataSource.setPassword(password);
    return dataSource;

    }
}
  1. xml需要先加载properties文件

或在最终引入的配置类中添加

@Bean
public PropertySourcesPlaceholderConfigurer createPropertySourcesPlaceholderConfigurer(){
    return new PropertySourcesPlaceholderConfigurer();
}

你可能感兴趣的:(数据库在Spring中配置)