数据连接池注解学习入门

  1. 1. 数据源的手动创建
    1. 1.1. 读取jdbc.properties配置文件创建连接池
    2. 1.2. 创建C3P0连接池
    3. 1.3. 测试加载核心配置类创建Spring容器

数据源的手动创建

  1. @Configuration
  2. @ComponentScan
  3. @Import
1
2
3
4
5
@Configuration
@ComponentScan("com.lan")
@Import({DataSourceConfiguration.class})
public class SpringConfiguration {
}

读取jdbc.properties配置文件创建连接池

  1. @PropertySource
  2. @value
1
2
3
4
5
6
7
8
9
10
11
12
@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;
.....
}

创建C3P0连接池

@Bean

1
2
3
4
5
6
7
8
9
10
@Bean(name="dataSource")
public DataSource getDataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}

测试加载核心配置类创建Spring容器

1
2
3
4
5
6
7
8
9
10
11
12
@Test
public void testAnnoConfiguration() throws Exception {
ApplicationContext applicationContext = new
AnnotationConfigApplicationContext(SpringConfiguration.class);
UserService userService = (UserService)
applicationContext.getBean("userService");
userService.save();
DataSource dataSource = (DataSource)
applicationContext.getBean("dataSource");
Connection connection = dataSource.getConnection();
System.out.println(connection);
}