@Configuration
作用:指定当前类是个配置类
注意:当该类为AnnotationConfigApplicationContext的参数时可以不写
@ComponentScan( basePackages = "com")
作用:指定要扫面的包
@Bean
作用:把当前方法的返回值作为bean对象存储到容器中
属性:name用于指定bean的id,默认值是当前方法的名称
注意:当我们使用注解配置方法时,参数回去spring容器中找对应的类型
@Bean(name = "runner")
public QueryRunner createQueryRunner(DataSource source)
{
return new QueryRunner(source)
}
@Import
作用:用于扫描其他配置类字节码,使用import注解的是父配置类,我们导入的就是子配置类
@Qualifier(value = "d1")作用于参数中指定类型
public class JDBCconfi {
@Bean(name = "runner")
public QueryRunner createQueryRunner(@Qualifier(value = "d1") DataSource source)
{
return new QueryRunner(source);
}
@Bean(name = "d1")
public DataSource creeateDataSource()
{
try {
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
comboPooledDataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
comboPooledDataSource.setJdbcUrl("jdbc:mysql:///db1");
comboPooledDataSource.setUser("root");
comboPooledDataSource.setPassword("zheng");
return comboPooledDataSource;
} catch (PropertyVetoException e) {
throw new RuntimeException(e);
}
}
}
配置类
@Configuration
@ComponentScan( basePackages = {"com"})
public class Configurtion {
@Bean(name = "runner")
public QueryRunner createQueryRunner(DataSource source)
{
return new QueryRunner(source);
}
@Bean(name = "dataSource")
public DataSource creeateDataSource()
{
try {
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
comboPooledDataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
comboPooledDataSource.setJdbcUrl("jdbc:mysql:///db1");
comboPooledDataSource.setUser("root");
comboPooledDataSource.setPassword("zheng");
return comboPooledDataSource;
} catch (PropertyVetoException e) {
throw new RuntimeException(e);
}
}
}
网友评论