(Spring)基于注解实现账户的CRUD操作案例

文章目录

    • 一、bean.xml
    • 二、AccountDaoImpl.java
    • 三、AccountServiceImpl.java
    • 四、测试类

一、bean.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
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!--告知Spring在创建容器时,要扫描的包,配置所需要的标签不是在beans的约束中
    而是一个名为context的名称空间和约束中-->
    <context:component-scan base-package="mybatis"></context:component-scan>

    <!--配置QueryRunner-->
    <!--防止多个账户使用,所以这里使用多例模式-->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <!--注入数据源-->
        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </bean>
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--连接数据库的必备信息-->
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
</beans>

二、AccountDaoImpl.java

@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {

    @Autowired
    private QueryRunner runner;

    @Override
    public List<Account> findAllAccount() {
        try {
            String sql = "select * from account";
            return runner.query(sql,new BeanListHandler<Account>(Account.class));
        } catch (Exception e) {
           throw new RuntimeException(e);
        }
    }
}

三、AccountServiceImpl.java

@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    @Override
    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }
}

四、测试类

public class AccountServiceTest {
    @Test
    public void testFindAll(){
        //1.获取spring容器
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        AccountService as = (AccountService) ac.getBean("accountService");
        //3.执行方法
        List<Account> accounts = as.findAllAccount();
        for (Account account : accounts) {
            System.out.println(account);
        }
    }
}

你可能感兴趣的:(Spring,学习笔记,spring,mysql,数据库,ioc)