使用 spring 的 IoC 的实现账户的CRUD(2)双层实现+注解开发

本文展示了如何在Spring框架中使用注解进行bean的定义和依赖注入。@Component是bean的基础注解,@Autowired自动按类型注入依赖,而@Qualifier用于按id注入。示例中,AccountDAO和AccountService通过注解与XML配置结合,实现数据查询功能。最后,文章提到了完全注解开发,通过@Configuration和@Bean注解替代XML配置文件。
摘要由CSDN通过智能技术生成

在http://t.csdn.cn/yucl4的基础上进行注解开发
【分析】
在这里插入图片描述

  • xml文件其中spring容器中的bean,
  • 因此通过注解把这些放到容器中即可

@component:相当xml中的bean的id:

  • 如果不指定 value 属性,默认 bean 的 id 是当前类的类名, 首字母小写。
  • @Controller @Service @Repository是三个衍生

@Autowired

  • 自动按照类型注入。
  • 当使用注解注入属性时,setter 方法可以省略
  • 它只能注入其他 bean 类型(spring容器中有的)。
  • 当有多个类型匹配时,使用要注入的对象变量名称作为 bean 的 id,在 spring 容器查找,找到了也可以注入成功。
  • @qualifier:按照id注入,必须与@Autowired搭配
package com.kfm.spring.dao;

import com.kfm.spring.model.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.SQLException;

/**
 * @author jkk
 */
@Component("accountdao")
public class IAccountdao implements Accountdao{

    @Autowired
    private QueryRunner queryRunner;
//    public void setQueryRunner(QueryRunner queryRunner){
//        this.queryRunner = queryRunner;
//    }
    @Override
    public Account findByid(int id) {
        String sql = "select * from account where id = ?";
        try {
            Account account = queryRunner.query(sql,new BeanHandler<>(Account.class),id);
            return account;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }
}

package com.kfm.spring.service;

import com.kfm.spring.dao.Accountdao;
import com.kfm.spring.model.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author jkk
 */
@Component("accountservice")
public class IAccountService implements AccounrService{
    @Autowired
    private Accountdao accountdao;
//    public  void setAccountdao(Accountdao accountdao){
//        this.accountdao = accountdao;
//    }
    @Override
    public Account findByid(int id) {
        return accountdao.findByid(id);
    }
}

.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
">


    <context:component-scan base-package="com.kfm.spring" ></context:component-scan>
    
    <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
        <constructor-arg name="ds" ref="datasource"></constructor-arg>
    </bean>
    <bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/web"></property>
        <property name="user" value="root"></property>
        <property name="password" value=""></property>
    </bean>
    </beans>

可以注意到,现在还不是完全的注解开发,只是替换了两个,既然两个用注解替换,那么如何从spring的容器中找到
在这里插入图片描述
@Resource

  • 不属于spring的注解,属于java的注解
  • 默认按照名字去找
  • 有两个属性name和type
  • 如果同时指定name和type,则会找到一个唯一的值
  • 如果只指定name,那么会按照name找,找不到报异常
  • 如果只指定type,那么先按照type找,找不到异常,找到多个,根据字段名匹配取

在这里插入图片描述
在这里插入图片描述
如何进行完全注解开发——完全不需要.xml文件

package com.kfm.spring.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * @author jkk
 */
@Configuration
@ComponentScan({"com.kfm.spring"})
public class SpringConfig {



    @Bean(name = "datasource")
    public DataSource getDatasource(){
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        try {
            comboPooledDataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
            comboPooledDataSource.setJdbcUrl("jdbc:mysql://localhost:3306/web");
            comboPooledDataSource.setUser("root");
            comboPooledDataSource.setPassword("");
        } catch (PropertyVetoException e) {
            throw new RuntimeException(e);
        }
        return comboPooledDataSource;
    }
    @Bean(name = "queryRunner")
    public QueryRunner getQueryRunner(DataSource dataSource){
        return  new QueryRunner(dataSource);

    }
}

测试‘

package com.kfm.spring.service;

import com.kfm.spring.config.SpringConfig;
import com.kfm.spring.dao.Accountdao;
import com.kfm.spring.model.Account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.junit.Assert.*;

@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(locations = "classpath:bean.xml")
@ContextConfiguration(classes = SpringConfig.class)
public class IAccountServiceTest {
    @Autowired
    private AccounrService accounrService;
    @Test
    public void test1FindByid(){
        Account account = accounrService.findByid(1);
        System.out.println(account);
    }


    @Test
    public void testFindByid() {
        ApplicationContext cx = new AnnotationConfigApplicationContext(SpringConfig.class);
        AccounrService accounrService = (AccounrService) cx.getBean("accountservice");
        Account account = accounrService.findByid(1);
        System.out.println(account);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值