创建配置类SpringConfiguration
@ComponentScan("com.itheima")
@Import(JdbcConfig.class)//用于导入其他的配置类
@PropertySource("classpath:jdbcConfig.properties")//用于指定properties文件的位置
public class SpringConfiguration {
}
其他配置类JdbcConfig
public class JdbcConfig {
@Value("${jdbc.driver}")//从jdbcConfig.properties中取
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean(name = "runner")
@Scope("prototype")
public QueryRunner createQueryRunner (@Qualifier("ds2") DataSource dataSource){
return new QueryRunner(dataSource);
}
@Bean(name = "ds2")
public DataSource createDataSource(){
ComboPooledDataSource ds = new ComboPooledDataSource();
try {
ds.setDriverClass(driver);
ds.setJdbcUrl(url);
ds.setUser(username);
ds.setPassword(password);
return ds;
} catch (Exception e){
throw new RuntimeException(e);
}
}
}
resource下创建jdbcConfig.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring
jdbc.username=root
jdbc.password=123456
测试
@RunWith(SpringJUnit4ClassRunner.class)//JUnit环境
@ContextConfiguration(classes = SpringConfiguration.class)
//locations:指定xml文件的位置,加上classpath关键字,表示在类路径下
//classes:指定注解类所在地位置,此处使用注解类
public class AccountServiceTest {
@Autowired
private AccountService as =null;
@Test
public void testFindAll(){
List<Account> accounts = as.findAllAccount();
for (Account account : accounts) {
System.out.println(account);
}
}