基于注解获取容器
public void test1(){
// ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
ApplicationContext ac=new AnnotationConfigApplicationContext(SpringConfig.class);
IAccountService as=ac.getBean("accountService",IAccountService.class);
List<Account> accounts=as.findAllAccount();
for (Account account : accounts) {
System.out.println(account);
}
}
配置类
@Configuration
@ComponentScan(basePackages = "com.zzq")
public class SpringConfig {
@Bean
public QueryRunner createQueryRunner(DataSource dataSource){
return new QueryRunner(dataSource);
}
}
@Configuration
作用:
指定该类是一个配置类,它修饰的类的作用和bean.xml一样
属性:
当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写
@ComponentScan
作用:
指定要扫描的包
属性:
value:它和basePackages作用一样,都是用于指定创建容器时要扫描的包
我们使用此注解就等同于在xml中配置了
<context:component-scan base-package=“com.zzq”></context:component-scan>
@Bean
作用:
用于把当前方法的返回值作为bean对象存入spring的ioc容器中
属性:
name:用于指定bean的id,当不写时,默认值时当前方法的名称
细节:私用注解配置方法时,如果方法有参数,spring框架回去容器中查找有没有可用的bean对象,查找的方式和Autowired注解的一样
@Import
属性:
value:用于指定那个其他配置类的字节码。有import注解的类是父配置类,导入的类是子配置类
@ComponentScan("com.zzq")
@Import(JdbcConfig.class)
public class SpringConfig {
}
@Configuration
public class JdbcConfig {
@Bean(name="runner")
public QueryRunner createQueryRunner(DataSource dataSource){
return new QueryRunner(dataSource);
}
// 创建数据源对象
@Bean(name="dataSource")
public DataSource createDatasource() throws PropertyVetoException {
ComboPooledDataSource ds=new ComboPooledDataSource();
ds.setDriverClass("com.mysql.jdbc.Driver");
ds.setJdbcUrl("jdbc:mysql://localhost:3306/eesy");
ds.setUser("root");
ds.setPassword("q1w23620001100");
return ds;
}
}
@PropertySource
作用:
指定properties文件的位置
属性:
value:指定文件路径(classpath表示类路径下)
SpringConfig如下
@ComponentScan("com.zzq")
@Import(JdbcConfig.class)
@PropertySource(value="classpath:jdbcConfig.properties")
public class SpringConfig {
}
jdbcConfig.properties如下
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/eesy
jdbc.username=root
jdbc.password=q1w23620001100