配置数据源(数据库连接池)
描述:
1、创建数据库的配置文件,例如jdbc.properties
2、创建数据源连接类,并使用注解配置连接信息
其中,
@PropertySource:引入配置文件,参数为数据库配置文件位置;
@Value:给指定变量绑定具体值,参数“${配置文件中的key值}”,获取key对应的value
@Bean:将具体数据库连接信息初始化并放入spring容器,参数为该连接信息取的别名
@PropertySource("classpath:jdbc.properties")
public class DataSourceConfiguration {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean("dataSource")
public DataSource getDataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}
}
3、创建主配置文件,并将数据库连接配置类导入
其中,
@Configuration:申明该类为spring主配置类;
@ComponentScan:组件扫描,参数为扫描范围;
@Import:导入其它配置类,参数为被导入配置类的字节码文件
@Configuration
@ComponentScan("com.spring")
@Import(DataSourceConfiguration.class)
public class SpringConfiguration {
}
4、使用或测试(使用spring-test测试)
使用spring-test需要在pom.xml中指明spring-test坐标;
其中,
@RunWith:指明所依赖的测试核心;
@ContextConfiguration:指明测试的配置类;
@Autowired:自动为变量生成set和get方法;
@Test:声明此方法为测试方法;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringJunitText {
@Autowired
private UserService userService;
@Autowired
private DataSource dataSource1;
@Test
public void test() throws SQLException {
userService.save();
System.out.println(dataSource1.getConnection());
}
}