Java框架_Spring5_day04_IOC(DBUtils)

目录

五、基于注解的 IOC 配置

六、使用 Spring 的 IOC 实现账户的CRUD

6.1 使用 XML 配置 IOC

6.2 使用注解配置 IOC


五、基于注解的 IOC 配置

以下注解是用于创建对象的​,他们的作用就和在XML配置文件中编写一个<bean>标签实现的功能是一样的

(1)@Component:

        作用:用于把当前类对象存入spring容器中​

        属性:​ * value:用于指定bean的id。当我们不写时,它的默认值是当前类名,且首字母改小写。

(2)Spring中提供了@Component的衍生注解

  • @Controller:用来修饰WEB层类(控制层)(springMVC延用了该注解)

  • @Service:用来修饰service层类(业务层)

  • @Repository:用来修饰DAO层类(持久层)

        以上三个注解他们的作用和属性与Component是一模一样。​ 他们三个是spring框架为我们提供明确的三层使用的注解,使我们的三层对象更加清晰。

以下注解是用于注入数据的,它们的作用就和在xml配置文件中的bean标签中写一个<property>标签的作用是一样的​ @Autowired: 基于spring

       作用:自动按照类型注入。只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功。如果ioc容器中没有任何bean的类型和要注入的变量类型匹配,则报错。​ 如果Ioc容器中有多个类型匹配时:先按照类型匹配,如果不能匹配上,会按照属性的名称进行匹配​

       出现位置:​ 可以是变量上,也可以是set方法上​

       细节:在使用注解注入时,set方法就不是必须的了。​

@Qualifier: 配合@Autowired注解一起使用

       作用:在按照类型注入的基础之上再按照名称注入。​

       属性:​ value:用于指定注入bean的id。​

@Resource​ JSR-250标准(基于jdk)

       作用:直接按照bean的id名称注入。如果id属性不存在,可以再按照类型注入。它可以独立使用​

       属性:​ name:用于指定bean的id,如果指定name,只能按照bean的id注入,不能按照类型注入。​ 注意:

以上三个注入都只能注入其他bean类型的数据,而基本类型和String类型无法使用上述注解实现(使用@Value)。

以下注解是用于改变作用范围的,他们的作用就和在bean标签中使用scope属性实现的功能是一样的​

@Scope

       作用:用于指定bean的作用范围​

       属性:​ value:指定范围的取值。

       常用取值:singleton prototype

AccountDaoImpl.java

package com.cpz.dao.impl;

import com.cpz.dao.AccountDao;
import org.springframework.stereotype.Repository;

@Repository(value = "accountDao")
public class AccountDaoImpl implements AccountDao {
    public void save() {
        System.out.println("执行AccountServiceImpl中的save方法....");
    }
}

AccountServiceImpl.java

@Service(value = "accountService")
@Scope(value = "singleton")
public class AccountServiceImpl implements AccountService {

    //@Autowired
    //@Qualifier(value = "accountDao")
    @Resource(name = "accountDao2")
    AccountDao accountDao;

    @Value(value = "xixi")
    String msg;

    public AccountServiceImpl(){
        System.out.println("构造方法...");
    }

    public void saveAccount() {
        System.out.println("执行AccountServiceImpl中的saveAccount方法...." + msg);
        accountDao.save();
    }
    @PostConstruct
    public void init(){
        System.out.println("初始化...");
    }
    @PreDestroy
    public void destroy(){
        System.out.println("销毁...");
    }
}

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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="com.cpz"></context:component-scan>

</beans>

六、使用 Spring 的 IOC 实现账户的CRUD

6.1 使用 XML 配置 IOC

导入坐标,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.cpz</groupId>
    <artifactId>spring_account_xmlioc</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</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.6</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
    </dependencies>
</project>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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">

    <!-- 使用import标签导入其他配置文件 -->
    <import resource="classpath:applicationContext-dao.xml"></import>
    <import resource="classpath:applicationContext-service.xml"></import>
    <import resource="classpath:applicationContext-dbutils.xml"></import>

</beans>

applicationContext-dao.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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">


    <!--配置Dao对象-->
    <bean id="accountDao" class="com.cpz.dao.impl.AccountDaoImpl">
        <property name="queryRunner" ref="queryRunner"></property>
    </bean>

</beans>

applicationContext-service.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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">

    <!-- 配置Service -->
    <bean id="accountService" class="com.cpz.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>
</beans>

applicationContext-dbutils.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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">

    <!-- 与jdbc.properties属性文件相关联 -->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

    <!--配置QueryRunner,设置prototype为多例,表示每次调用都获取一个新的连接对象-->
    <bean id="queryRunner" 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="${jdbc.driverClass}"></property>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
</beans>

jdbc.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///spring
jdbc.user=root
jdbc.password=1234

AccountDao.java

package com.cpz.dao;

import com.cpz.domain.Account;

import java.util.List;

public interface AccountDao {

    public List<Account> findAll();

    public Account findById(Integer id);

    public void save(Account account);

    public void update(Account account);

    public void delete(Integer id);

}

AccountDaoImpl.java

package com.cpz.dao.impl;

import com.cpz.dao.AccountDao;
import com.cpz.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;

public class AccountDaoImpl implements AccountDao {

    QueryRunner queryRunner;

    public void setQueryRunner(QueryRunner queryRunner) {
        this.queryRunner = queryRunner;
    }

    public List<Account> findAll() {
        List<Account> list = null;
        try {
            list = queryRunner.query("select * from account", new BeanListHandler<Account>(Account.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    public Account findById(Integer id) {
        List<Account> list = null;
        try {
            list = queryRunner.query("select * from account where id = ?",new BeanListHandler<Account>(Account.class),id);
            if (list == null && list.size() == 0){
                return null;
            }else if (list.size() > 1){
                new RuntimeException("查询结果大于一");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list.get(0);
    }

    public void save(Account account) {
        try {
            queryRunner.update("insert into account (name,money) values (?,?)",account.getName(),account.getMoney());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void update(Account account) {
        try {
            queryRunner.update("update account set name = ?,money = ? where id = ?",account.getName(),account.getMoney(),account.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void delete(Integer id) {
        try {
            queryRunner.update("delete from account where id = ?",id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

AccountService.java

package com.cpz.service;

import com.cpz.domain.Account;

import java.util.List;

public interface AccountService {

    public List<Account> findAccountAll();

    public Account findAccountById(Integer id);

    public void saveAccount(Account account);

    public void updateAccount(Account account);

    public void deleteAccount(Integer id);

}

AccountServiceImpl.java

package com.cpz.service.impl;

import com.cpz.dao.AccountDao;
import com.cpz.domain.Account;
import com.cpz.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.List;

public class AccountServiceImpl implements AccountService {

    AccountDao accountDao;

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    public List<Account> findAccountAll() {
        List<Account> list = accountDao.findAll();
        return list;
    }

    public Account findAccountById(Integer id) {
        Account account = accountDao.findById(id);
        return account;
    }

    public void saveAccount(Account account) {
        accountDao.save(account);
    }

    public void updateAccount(Account account) {
        accountDao.update(account);
    }

    public void deleteAccount(Integer id) {
        accountDao.delete(id);
    }
}

SpringTest 测试类

package com.cpz.test;

import com.cpz.domain.Account;
import com.cpz.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class SpringTest {

    @Test
    public void findAll(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountService accountService = ac.getBean("accountService", AccountService.class);
        List<Account> list = accountService.findAccountAll();
        for (Account account : list) {
            System.out.println(account);
        }
    }

    @Test
    public void findById(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountService accountService = ac.getBean("accountService", AccountService.class);
        Account account = accountService.findAccountById(1);
        System.out.println(account);
    }

    @Test
    public void save(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountService accountService = ac.getBean("accountService", AccountService.class);
        Account account = new Account();
        account.setName("ccc");
        account.setMoney(200f);
        accountService.saveAccount(account);
    }

    @Test
    public void update(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountService accountService = ac.getBean("accountService", AccountService.class);
        Account account = accountService.findAccountById(3);
        account.setName("张三");
        accountService.updateAccount(account);
    }

    @Test
    public void delete(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountService accountService = ac.getBean("accountService", AccountService.class);
        accountService.deleteAccount(3);
    }
}

6.2 使用注解配置 IOC

       这里使用的注解就是本文开头所讲的那些,更多的注解用法将在下一章详细阐述。

6.3 应用

今后企业开发的时候:一般配置文件(xml)+  注解混合使用

配置文件:

  • 第三方提供的对象(QueryRunner、C3P0),可以由配置文件XML完成

  • 自己创建的对象(Controller、Service、Dao、工具类Utils),可以由注解进行完成

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值