本文是在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); } }
原文
https://segmentfault.com/a/1190000022155849
本站部分文章源于互联网,本着传播知识、有益学习和研究的目的进行的转载,为网友免费提供。如有著作权人或出版方提出异议,本站将立即删除。如果您对文章转载有任何疑问请告之我们,以便我们及时纠正。PS:推荐一个微信公众号: askHarries 或者qq群:474807195,里面会分享一些资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化这些成为架构师必备的知识体系。还能领取免费的学习资源,目前受益良多

转载请注明原文出处:Harries Blog™ » 说说我的spring入门5–ioc注解进阶