spring 1.x 时代主要使用xml配置和java代码的方式java
随着JDK 1.5带来的注解支持,Spring2.x可使用注解对Bean进行申明和注入,大大的减小了xml配置文件,同时也大大简化了项目的开发。
一、 应用的基本配置用xml,好比:数据源、资源文件等;
二、 业务开发用注解,好比:Service中注入bean等;spring
从Spring3.x开始提供了Java配置方式,使用Java配置方式能够更好的理解你配置的Bean,如今咱们就处于这个时代,而且Spring4.x和Springboot都推荐使用java配置的方式。数据库
/** * @Bean 至关与获取一个bean,相似xml 方式的配置,方法名就是xml方式配置bean的id,所 *以方法不用getDataSource, id 通常不用getXXX. * @return */ **@Bean(destroyMethod = "close")**//destroyMethod = "close" public DataSource dataSource() { BoneCPDataSource boneCPDataSource = new BoneCPDataSource(); // 数据库驱动 boneCPDataSource.setDriverClass(jdbcDriverClassName); // 相应驱动的jdbcUrl boneCPDataSource.setJdbcUrl(jdbcUrl); // 数据库的用户名 boneCPDataSource.setUsername(jdbcUsername); // 数据库的密码 boneCPDataSource.setPassword(jdbcPassword); // 检查数据库链接池中空闲链接的间隔时间,单位是分,默认值:240,若是要取消则设置为0 boneCPDataSource.setIdleConnectionTestPeriodInMinutes(60); // 链接池中未使用的连接最大存活时间,单位是分,默认值:60,若是要永远存活设置为0 boneCPDataSource.setIdleMaxAgeInMinutes(30); // 每一个分区最大的链接数 boneCPDataSource.setMaxConnectionsPerPartition(100); // 每一个分区最小的链接数 boneCPDataSource.setMinConnectionsPerPartition(5); final Connection connection; try { connection = boneCPDataSource.getConnection(); System.out.println("数据库链接为:"); System.out.println(connection); } catch (SQLException e) { e.printStackTrace(); } return boneCPDataSource; }
**备注:** 一、@Bean(destroyMethod = "close")以便Spring容器关闭时,数据源可以正常关闭;销毁方法调用close(),是将链接关闭,并非真正的把资源销毁。 二、同时咱们能够注意BoneCPDataSource 对数据源的设置。