本文是在spring入门4的基础上,采用注解进行改进的。
在bean.xml配置中,下面这条语句是指配置spring扫描注解的文件夹。
<context:component-scan base-package="com.itheima"></context:component-scan>
我们可以新建一个SpringConfiguration类,@Configuration指明这是一个配置类,与bean.xml等效。@ComponentScan(basePackages = {"com.itheima"})配置spring扫描注解的文件夹。
@Configuration
@ComponentScan(basePackages = {"com.itheima"})
public class SpringConfiguration {
@Bean(name="runner")
public QueryRunner createQueryRunner(DataSource dataSource){
return new QueryRunner(dataSource);
}
}
配置容器对象
下面的代码是bean.xml中把QueryRunner 放入容器中的实现方式,并且用constrouctor-arg为其配置构造方法注入dataSource。
上面SpringConfiguration类中的createQueryRunner方法通过接收一个dataSource参数返回QueryRunner对象,只要再把返回对象放到spring容器中即可。 @Bean可以实现Bean化。
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
事实上,上面需要接收一个dataSource参数,spring框架会去容器中查找该参数对应的bean对象,查找方式与AutoWried一样。因此我们需要把dataSource放入spring容器
@Bean(name="dataSource")
public DataSource createDataSource(){
try {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass("com.mysql.cj.jdbc.Driver");
ds.setJdbcUrl("jdbc:mysql://localhost:3306/myspring?serverTimezone=GMT%2B8");
ds.setUser("root");
ds.setPassword("52wendyma");
return ds;
}catch(Exception e){
throw new RuntimeException(e);
}
}
注意此时需要用AnnotationConfigApplicationContext对象读取配置文件对象。
public void testFindAll() {
//ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
IAccountService as = ac.getBean("accountService",IAccountService.class);
//3.执行方法
List<Account> accounts = as.findAllAccounts();
for(Account account : accounts){
System.out.println(account);
}
}