11. 基于半注解半xml的IoC案例

该博客介绍了如何在Spring框架中采用半注解半XML配置的方式来实现IoC容器的管理。案例涉及数据库account表的CRUD操作,通过注解处理项目中的自定义类和关系,而XML文件用于处理注解扫描、类库中的bean创建及依赖注入。文章详细讲解了项目的目录结构、pom.xml配置、domain包中的Account类、dao层、service层的实现,以及bean.xml配置文件和测试类的编写。

需求:在数据库中创建一个account表,使用spring+dbutils完成对account的增删改查

在这个案例中,并没有完全使用注解或者完全使用xml配置,而是使用半注解半xml配置的方式

注解方式处理:自己写的类及其之间的关系使用注解的方式创建bean、注入依赖、管理bean的作用范围、管理bean的生命周期

xml配置文件处理:注解扫描、类库或jar包中的类的bean的创建、注入依赖,管理bean的作用范围、管理bean的生命周期(比如连接数据库)

一 项目的目录结构

二 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.itheima</groupId>
    <artifactId>day02_eesy_02xmlIoC</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.4</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.44</version>
        </dependency>

        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>6</source>
                    <target>6</target>
                </configuration>
            </plugin>

        </plugins>
    </build>
</project>

二 domain包中的Account类

public class Account {
    private int id;
    private String name;
    private float money;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public float getMoney() {
        return money;
    }
    public void setMoney(float money) {
        this.money = money;
    }
    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

三 dao层

使用注解方式的话,不需要给private QueryRunner runner写setter方法

@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {
    @Resource(name="runner")
    private QueryRunner runner;  //使用注解方式的话,不需要给private QueryRunner runner写setter方法
    @Override
    public List<Account> findAllAccount() {
        try{
            return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public Account findAccountById(Integer accountId) {
        try{
            return runner.query("select * from account where id = ? ",new BeanHandler<Account>(Account.class),accountId);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public void saveAccount(Account account) {
        try{
            runner.update("insert into account(name,money)values(?,?)",account.getName(),account.getMoney());
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public void updateAccount(Account account) {
        try{
            runner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public void deleteAccount(Integer accountId) {
        try{
            runner.update("delete from account where id=?",accountId);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

四 service层

使用注解方式的话,不需要给accountDao写setter方法

@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Resource(name="accountDao")
    private AccountDao accountDao;//使用注解方式的话,不需要给accountDao写setter方法
    public List<Account> findAllAccount() {
        List<Account> accountList=accountDao.findAllAccount();
        return accountList;
    }
    public Account findAccountById(Integer accountId) {
        Account account=accountDao.findAccountById(accountId);
        return account;
    }
    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }
    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }
    public void deleteAccount(Integer acccountId) {
        accountDao.deleteAccount(acccountId);
    }
}

五 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">
    <!--扫描注解-->
    <context:component-scan base-package="com.itheima"></context:component-scan>

    <!--让spring帮我们创建bean-->
    <!--配置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/eesy"></property>
        <property name="user" value="root"></property>
        <property name="password" value="gao1994"></property>
    </bean>
</beans>

六 测试类

public class AccountServiceTest {
    //查询所有
    @Test
    public void findAllAccountTest(){
        //获取spring容器
        ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
        //获取bean
        AccountService accountService = ac.getBean("accountService", AccountService.class);
        //执行方法
        List<Account> allAccount = accountService.findAllAccount();
        for(Account account:allAccount){
            System.out.println(account);
        }
    }
    //查询一个
    @Test
    public void findAccountByIdTest(){
        //获取spring容器
        ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
        //获取bean
        AccountService accountService = ac.getBean("accountService", AccountService.class);
        //执行方法
        Account account = accountService.findAccountById(1);
        System.out.println(account);
    }
    //保存
    @Test
    public void saveAccountTest(){
        //获取spring容器
        ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
        //获取bean
        AccountService accountService = ac.getBean("accountService", AccountService.class);
        //执行方法
        Account account=new Account();
        account.setName("gao");
        account.setMoney(100000);
        accountService.saveAccount(account);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值