IDEA: 如 jdbc.properties配置文件存在resource资源文件夹里
方法一:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| @Test
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
|
@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("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); }
}
|