spring框架:(五)全注解IOC小案例

说明:舍弃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);
    }
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值