(1)创建一个配置类,作用与bean.xml一致
@Configuration:表明当前类是一个配置类
@ComponentScan:用于通过注解指定spring在创建容器时要扫描的包
@ComponentScan (value = "cn.rzpt")与 @ComponentScan (basePackages = "cn.rzpt")一样
<context:component-scan base-package="cn.rzpt"></context:component-scan>
(2)@Bean:用于把当前方法的返回值作为bean对象存入spring的ioc容器中
属性:name:用于指定bean的id,当不写明时默认值是当前方法的名称
@Bean(name = "runner")//目前是单例模式,多例需要加:@Scope("prototype")
public QueryRunner createQueryRunner(DataSource dataSource){
return new QueryRunner((dataSource));
}
@Bean(name = "dataSource")
public DataSource createDataSource(){
ComboPooledDataSource dataSource = new ComboPooledDataSource();
try {
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/student");
dataSource.setUser("root");
dataSource.setPassword("zxn682899");
return dataSource;
} catch (PropertyVetoException e) {
e.printStackTrace();
return null;
}
}
(3)当使用注解配置方法时,如果方法有参数,spring框架去容器中查找有没有可以使用的bean对象,查找方法和@Autowired注解的一样。
(4)删除bean.xml的内容
(5)修改ApplicationContext实例化方式
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfigration.class);
(6)使用properties文件
jdbccon.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/student
jdbc.username=root
jdbc.password=1234
@import:用于导入其它的配置类,属性:value:用于指定其他配置类的字节码,当使用import的注解之后,有import注解的类就不导入父配置类,而导入的都是子配置类
@Import(JdbcConfig.class)
配置类:
public class JdbcConfig {
//从jdbccon.properties获取到值
@Value("${jdbc.driver}")
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(DataSource dataSource){
return new QueryRunner((dataSource));
}
@Bean(name = "dataSource")
public DataSource createDataSource(){
ComboPooledDataSource dataSource = new ComboPooledDataSource();
try {
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
} catch (PropertyVetoException e) {
e.printStackTrace();
return null;
}
}
}
@PropertySource:用于指定properties文件的位置。属性:value:指定文件的名称和路径:关键字:classpath:表示配置文件在类路径下
@ComponentScan("cn.rzpt")
@Import(JdbcConfig.class)
@PropertySource(value = "classpath:jdbcConfig.properties")
public class SpringConfigration {
}
(7)如果调用别人写的类库,一般情况写在bean.xml文件配置;
自己写的类,多数可以使用注解
(8)@Qualifier(“”)可以定义在方法的参数上,指明具体的参数来源,可以不用@Autowired配合支持