说明:舍弃xml配置,全注解Ioc;基于 “spring框架:(四)基于xml的 IOC小案例” 的更改;
如有必要请参见:spring框架:(四)基于xml的 IOC小案例
spring框架:(三)IOC注解
-
1、 新增注解
-
@Configuration
-
@ComponentScan
-
@Bean
-
注:此处未提及注解可参见:spring框架:(三)IOC注解
2、新增配置类代替xml
-
@Configuration //指定当前类是个配置类; @ComponentScan("com.it") //指定创建容器时要扫描的包,功能与xml配置中的<context:component-scan base-package="com.it"></context:component-scan> public class SpringConfing { /** * @Bean * 作用:将当前方法的返回值作为bean对象存入ioc容器 * 属性: name;指定bean的id,默认值为当前方法名首字母小写;返回值作为value */ @Bean("runner") @Scope("prototype") public QueryRunner creatQueryRunner(DataSource dataSource) { return new QueryRunner(dataSource); } @Bean("dataSource") public DataSource ceratDataSource() { ComboPooledDataSource cpd = new ComboPooledDataSource(); try { cpd.setDriverClass("com.mysql.jdbc.Driver"); cpd.setJdbcUrl("jdbc:mysql://localhost:3306/demo"); cpd.setUser("root"); cpd.setPassword("root"); } catch (PropertyVetoException e) { e.printStackTrace(); } return cpd; } }
3、因为删除了xml配置,因此要在交由Ioc容器管理的类上及需要资源注入的属性和方法上加注解
-
(1)dao层实现类
-
@Repository("demoDao") public class DemoDaoImpl implements DemoDao { @Autowired //可以@Resource代替,二者区别可参见:spring框架:(三)IOC注解 private QueryRunner runner; //此处以下代码不变,不再重复,可参考:spring框架:(四)基于xml的 IOC小案例
-
(2)service实现类
-
@Service("demoService") public class DemoServiceImpl implements DemoService { @Autowired //可以@Resource代替,二者区别可参见:spring框架:(三)IOC注解 private DemoDao demoDao; //此处以下代码不变,不再重复,可参考:spring框架:(四)基于xml的 IOC小案例
-
(3) test
-
public class DemoServiceTest { @Test public void testFindAll() { //1.获取容器 //在原来的测试类上只需修改获取容器的方式即可,其他不变;其他test相同 ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfing.class); //2.得到业务层方法 IDemoService service = ac.getBean("demoService", IDemoService.class); //3.执行查找方法 List<Demo> demoList = service.findAllDemo(); for (Demo demo : demoList) { System.out.println(demo); } }