1.创建一个类代替bean.xml
/**
* 该类是一个配置类:他的作用的bean.xml时一样的
* spring中的新注解
* Configuration
* 作用:指定当前类是一个配置类
* 细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可用不写
*
* ComponenyScan
* 作用:用于通过注解指定spring在创建容器时要扫描的包
* 属性:value:和basePackages的作用是一样的,都是告知spring在创建容器时要扫描的包
* 使用此注解等同于在xml中配置了:<context:component-scan base-package="sise.cn"></context:component-scan>
*
* Bean
* 作用:用于把当前方法的返回值作为bean对象存入spring的ioc容器中
* 属性:name:用于指定Bean的id。默认值是当不写时,默认值是当前方法的名称
* 细节:当我们是用注解配置方法是,如果方法有参数,spring框架回去容器中查找有没有可用的bean对象
* 查找的方式和Autowired注解是一样。
*
* Import
* 作用:用于导入其他的配置类
* 属性: value:用于指定其他配置类的字节码文件,当我们使用Import的注解之后,有Import注解的类就是主配置(父配置类)导入的都是子配置类
*/
//@Configuration可不写,因为AnnotationConfigApplicationContext
@ComponentScan("sise.cn")
//@Import(JdbcConfig.class)当有其他配置类时可用此方法导入,导入的为子配置类
public class SpringConfiguration {
/**
* 用于创建一个QueryRunner对象
*
* @param dataSource
* @return
*/
@Bean(name = "runner")
public QueryRunner createQueryRunner(DataSource dataSource) {
return new QueryRunner(dataSource);
}
/**
* 创建数据源对象
*
* @return
*/
@Bean(name = "dataSource")
public DataSource createDaDataSource() {
try {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass("com.mysql.jdbc.Driver");
ds.setJdbcUrl("jdbc:mysql://localhost:3306/eesyioc");
ds.setUser("root");
ds.setPassword("root");
return ds;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
test:
**
* s使用junit单元测试:测试配置
*/
public class AccountServiceTest {
@Test
public void testFindAll() {
//1.获取容器对象
/*ClassPathXmlApplicationContext cs = new ClassPathXmlApplicationContext("bean.xml");*/
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
//2.得到业务层对象
IAccountService as = ac.getBean("accountService",IAccountService.class);
//3.执行方法
List<Account> accounts = as.findAllAccount();
for (Account account : accounts) {
System.out.println(account);
}
}
继续优化
把数据域独立出来,在resource创建jdbcConfig.properties
jdbc.driver("com.mysql.jdbc.Driver");
jdbc.url("jdbc:mysql://localhost:3306/eesyioc");
jdbc.username("root");
jdbc.password("root");
然后改造创建数据源对象
/ *
* propertySource
* 作用:用于指定properties文件的位置
* 属性:value:指定文件的名称和路径
* 关键字:classpath,表示类路径
*/
@ComponentScan("sise.cn")
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
/**
* 创建数据源对象
*
* @return
*/
@Bean(name = "dataSource")
public DataSource createDaDataSource() {
try {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass(driver);
ds.setJdbcUrl(url);
ds.setUser(username);
ds.setPassword(password);
return ds;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
选择xml和注解的方法原则:
一般封装在jar包的别人写好的用xml, 自己写的一般用注解配置