加载配置文件

  1. 1. 方法一:
  2. 2. 方法二: PropertySource注解:引入jdbc属性资源文件

​ IDEA: 如 jdbc.properties配置文件存在resource资源文件夹里

方法一:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
// 测试手动创建c3p0数据源(加载properties配置文件)
public void test3() throws Exception{
// 读取配置文件
ResourceBundle rb = ResourceBundle.getBundle("jdbc");
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(rb.getString("jdbc.driver"));
dataSource.setJdbcUrl(rb.getString("jdbc.url"));
dataSource.setUser(rb.getString("jdbc.username"));
dataSource.setPassword(rb.getString("jdbc.password"));
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}

方法二: PropertySource注解:引入jdbc属性资源文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* jdbc配置类
* PropertySource:引入jdbc属性资源文件
* classpath: 在resource资源包里面
*/
@PropertySource("classpath:jdbc.properties")
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;

@Value("${jdbc.url}")
private String url;

@Value("${jdbc.user}")
private String user;

@Value("${jdbc.password}")
private String password;

/**
* Bean注解:该注解只能写在方法上,表面该方法创建了一个对象,并放入spring容器
*/
@Bean("dataSource")
public DataSource createDataSource() throws PropertyVetoException {
// 创建数据源
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(user);
dataSource.setPassword(password);
return dataSource;
}

@Bean("jdbcTemplate")
public JdbcTemplate createJdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}

}