Spring框架学习总结第二天

Spring框架学习总结第二天

基于注解的IOC配置

引入

学习基于注解的 IoC 配置,大家脑海里首先得有一个认知,即注解配置和 xml 配置要实现的功能都是一样的,都是要降低程序间的耦合。只是配置的形式不一样。

关于实际的开发中到底使用xml还是注解,每家公司有着不同的使用习惯。所以这两种配置方式我们都需要掌握。

我们在讲解注解配置时,采用第一天的案例,把 spring 的 xml 配置内容改为使用注解逐步实现。

就是将第一天的基于xml的配置改为基于注解的配置

环境搭建

添加jar包
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.2.RELEASE</version>
    </dependency>

    <!--使得Resource注解可以使用-->
    <dependency>
        <groupId>javax.annotation</groupId>
        <artifactId>javax.annotation-api</artifactId>
        <version>1.3.1</version>
    </dependency>
</dependencies>
和xml配置对应的注解
曾经xml的配置
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl" scope="" init-method="" destroy-method="">
	<property name="" value="" ref=""></property>
</bean>
使用注解配置

用于创建对象的:他们的作用就和在xml配置文件中编写一个标签实现功能是一样的

Component:

作用:用于把当前类对象存入spring容器中
属性:value:用于指定bean的id。当我们不写时,它的默认值是当前类名,且首字母改小写

Controller:一般用在表现层

Service:一般用于业务层

Repository:一般用于持久层

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

用于注入数据的:他们的作用就和在xml配置文件中的bean标签中写一个标签作用是一样的

Autowired:

作用:自动按照类型注入,只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功
                   如果IOC容器中没有任何bean的类型和要注入的变量类型匹配,则报错
                   如果IOC容器中有多个类型匹配时:先通过数据类型确定范围,再通过变量名称确定匹配哪个,如果无法通过变量名称确定哪个,则报错,如果能,则运行成功
出现位置:可以是变量上,也可以是方法上
细节:在使用注解注入时,set方法就不是必须的了

Qualifier:需要和Autowired注解结合使用

作用:在按照类中注入的基础之上再按照名称注入,它在给类成员注入时不能单独使用,需要和Autowired注解一起使用,但是在给方法参数注入时可以(稍后再说)
属性:
value:用于指定注入bean的id

Resource:

作用:直接按照bean的id注入,他可以独立使用
属性:
name:用于指定bean的id

注意:以上三个注解都只能注入其他bean类型的数据,而基本数据类型和String类型无法使用上述注解实现。另外,集合类型的注入只能通过XML来实现。

Value:

作用:用于注入基本数据类型和String类型的数据
属性:
value:用于指定数据的值,他可以使用spring中的SpEL(也就是spring的el表达式)
SpEL的写法:${表达式}

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

Scope:

作用:用于指定bean的作用范围
属性:
value:指定范围的取值,常用取值:singleton prototype

和生命周期相关:了解,他们的作用就和在bean标签中使用init-method和destroy-method的作用是一样的

PreDestroy:

作用:用于指定销毁方法

PostConstruct:

作用:用于指定初始化方法
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名称空间和约束中,如上-->
    <!--此时就会扫描com.itheima下所有类的注解-->
    <context:component-scan base-package="com.itheima"></context:component-scan>
</beans>
编写持久层
package com.itheima.dao;

/**
 * 账户的持久层接口
 */
public interface IAccountDao {
    /**
     * 模拟保存账户
     */
    void saveAccount();
}
编写持久层实现类
package com.itheima.dao.impl;

import com.itheima.dao.IAccountDao;
import org.springframework.stereotype.Repository;

/**
 * 账户的持久层实现类
 */
@Repository("accountDao1")
public class AccountDaoImpl implements IAccountDao {
    public void saveAccount() {
        System.out.println("保存了账户11111111");
    }
}
package com.itheima.dao.impl;

import com.itheima.dao.IAccountDao;
import org.springframework.stereotype.Repository;

/**
 * 账户的持久层实现类
 */
@Repository("accountDao2")
public class AccountDaoImpl2 implements IAccountDao {
    public void saveAccount() {
        System.out.println("保存了账户22222222");
    }
}
编写业务层
package com.itheima.service;

/**
 * 账户业务层的接口
 */
public interface IAccountService {
    /**
     * 模拟保存账户
     */
    void saveAccount();
}
编写业务层实现类
package com.itheima.service.impl;

import com.itheima.dao.IAccountDao;
import com.itheima.dao.impl.AccountDaoImpl;
import com.itheima.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

/**
 * 账户的业务层实现类
 */
@Service("accountService")  //以下三个也都可以
//@Controller("accountService")
//@Component("accountService")
//@Repository("accountService")
//@Scope("prototype") //多例对象,spring无法销毁
public class AccountServiceImpl implements IAccountService {

    /*@Autowired
    @Qualifier("accountDao1")*/
    @Resource(name = "accountDao2")
    private IAccountDao accountDao = null;

    @PostConstruct
    public void init() {
        System.out.println("初始化方法执行了");
    }

    @PreDestroy
    public void destroy() {
        System.out.println("销毁方法执行了");
    }

    public void saveAccount() {
        accountDao.saveAccount();
    }
}
编写测试类用于测试注解配置
package com.itheima.ui;

import com.itheima.dao.IAccountDao;
import com.itheima.service.IAccountService;
import com.itheima.service.impl.AccountServiceImpl;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

/**
 * 模拟一个表现层,用于调用业务层
 */
public class Client {
    /**
     *
     * @param args
     */
    public static void main(String[] args) {
        //1.获取核心容器对象
//        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.根据id获取Bean对象,两种方式均可
        IAccountService as = (IAccountService) ac.getBean("accountService");
//        IAccountService as2 = (IAccountService) ac.getBean("accountService");
//        System.out.println(as);
//
//        IAccountDao adao = ac.getBean("accountDao",IAccountDao.class);
//        System.out.println(adao);
//        System.out.println(as == as2);
        as.saveAccount();
        ac.close();
    }
}

使用spring的IoC实现账户的CRUD

需求和技术要求

需求

实现账户的 CRUD 操作

技术要求

使用 spring 的 IoC 实现对象的管理

使用 QueryRunner 作为持久层解决方案

使用 c3p0 数据源

环境搭建
添加spring的jar包
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.2.RELEASE</version>
    </dependency>

    <!--提供新的SpringJUnit4ClassRunner测试方法,用于@RunWith(SpringJUnit4ClassRunner.class)注解自动创建容器-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>5.0.2.RELEASE</version>
    </dependency>

    <!--提供QueryRunner类执行sql语句-->
    <dependency>
        <groupId>commons-dbutils</groupId>
        <artifactId>commons-dbutils</artifactId>
        <version>1.4</version>
    </dependency>

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

    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.5.2</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
</dependencies>
创建数据库和表
CREATE DATABASE IF NOT EXISTS eesy
DEFAULT CHARACTER SET utf8mb4
DEFAULT COLLATE utf8mb4_0900_ai_ci;

use eesy;

create table account(
	id int primary key auto_increment,
	name varchar(40),
	money float
)character set utf8 collate utf8_general_ci;

insert into account(name,money) values('aaa',1000);
insert into account(name,money) values('bbb',1000);
insert into account(name,money) values('ccc',1000);
编写实体类
package com.itheima.domain;

import java.io.Serializable;

/**
 * 账户的实体类
 */
public class Account implements Serializable {

    private Integer id;
    private String name;
    private Float money;
    
}
编写持久层
package com.itheima.dao;

import com.itheima.domain.Account;

import java.util.List;

/**
 * 账户的持久层接口
 */
public interface IAccountDao {

    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 查询一个
     * @return
     */
    Account findAccountById(Integer accountId);

    /**
     * 保存
     * @param account
     */
    void saveAccount(Account account);

    /**
     * 更新
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 删除
     * @param acccountId
     */
    void deleteAccount(Integer acccountId);
}
编写持久层实现类
package com.itheima.dao.impl;

import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.util.List;

/**
 * 账户的持久层实现类
 */
public class AccountDaoImpl implements IAccountDao {

    private QueryRunner runner;

    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }

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

    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);
        }
    }

    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);
        }
    }

    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);
        }
    }

    public void deleteAccount(Integer accountId) {
        try{
            runner.update("delete from account where id=?",accountId);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
编写业务层
package com.itheima.service;

import com.itheima.domain.Account;

import java.util.List;

/**
 * 账户的业务层接口
 */
public interface IAccountService {

    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 查询一个
     * @return
     */
    Account findAccountById(Integer accountId);

    /**
     * 保存
     * @param account
     */
    void saveAccount(Account account);

    /**
     * 更新
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 删除
     * @param acccountId
     */
    void deleteAccount(Integer acccountId);

}
编写业务层实现类
package com.itheima.service.impl;

import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import com.itheima.service.IAccountService;

import java.util.List;

/**
 * 账户的业务层实现类
 */
public class AccountServiceImpl implements IAccountService{

    private IAccountDao accountDao;

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

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

    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }

    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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 配置Service -->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
        <!-- 注入dao set方法注入-->
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!--配置Dao对象-->
    <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
        <!-- 注入QueryRunner -->
        <property name="runner" ref="runner"></property>
    </bean>

    <!--配置QueryRunner scope="prototype"配置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?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=GMT%2B8"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
</beans>
编写测试类
package com.itheima.test;

import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 * 使用Junit单元测试,测试我们的配置
 */
public class AccountServiceTestOld {

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

    @Test
    public void testFindOne(){
        //1.获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        IAccountService as = ac.getBean("accountService", IAccountService.class);
        //3.执行方法
        Account account = as.findAccountById(1);
        System.out.println(account);
    }

    @Test
    public void testSave(){
        //1.获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        IAccountService as = ac.getBean("accountService", IAccountService.class);
        Account account = new Account();
        account.setName("ddd");
        account.setMoney(2000F);
        //3.执行方法
        as.saveAccount(account);
    }

    @Test
    public void testUpdate(){
        //1.获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        IAccountService as = ac.getBean("accountService", IAccountService.class);
        //3.执行方法
        Account account = as.findAccountById(4);
        account.setMoney(2500F);
        as.updateAccount(account);
    }

    @Test
    public void testDelete(){
        //1.获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        IAccountService as = ac.getBean("accountService", IAccountService.class);
        //3.执行方法
        as.deleteAccount(4);
    }

}
分析测试中的问题

通过上面的测试类,我们可以看出,每个测试方法都重新获取了一次 spring 的核心容器,造成了不必要的重复代码,增加了我们开发的工作量。这种情况,在开发中应该避免发生。

可以使用一种方法,把容器的获取定义到类中去。例如:

public class AccountServiceTestOld {
    private ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
    private IAccountService as = ac.getBean("accountService",IAccountService.class);
}

这种方式虽然能解决问题,但是扔需要我们自己写代码来获取容器。能不能测试时直接就编写测试方法,而不需要手动编码来获取容器呢?答案是肯定的,见下 Spring 整合 Junit

Spring整合Junit[掌握]

测试类中的问题和解决思路

问题

在测试类中,每个测试方法都有以下两行代码:

ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService as = ac.getBean("accountService",IAccountService.class);

这两行代码的作用是获取容器,如果不写的话,直接会提示空指针异常。所以又不能轻易删掉。

解决思路分析
使用Junit单元测试,测试我们的配置
1.应用程序的入口
	main方法
2.junit单元测试中,没有main方法也能执行
	junit集成了一个main方法
	该方法就会判断当前测试类中哪些方法有 @Test注解
	junit就让有Test注解的方法执行
3.junit不会管我们是否采用spring框架
	在执行测试方法时,junit根本不知道我们是不是使用了spring框架
	所以也就不会为我们读取配置文件/配置类创建spring核心容器
4.由以上三点可知:
	当测试方法执行时,没有IOC容器,就算写了Autowired注解,也无法实现注入
	即private IAccountService as = null;

针对上述问题,我们需要的是程序能自动帮我们创建容器。一旦程序能自动为我们创建 spring 容器,我们就无须手动创建了,问题也就解决了。

我们都知道,junit 单元测试的原理,但显然,junit 是无法实现的,因为它自己都无法知晓我们是否使用了 spring 框架,更不用说帮我们创建 spring 容器了。不过好在,junit 给我们暴露了一个注解,可以让我们替换掉它的运行器。

这时,我们需要依靠 spring 框架,因为它提供了一个运行器,可以读取配置文件(或注解)来创建容器。我们只需要告诉它配置文件在哪就行了。

配置步骤

第一步:导入需要的jar包

注意:当我们使用spring 5.x版本时,要求junit的jar必须是4.12及以上

<!--提供新的SpringJUnit4ClassRunner测试方法,用于@RunWith(SpringJUnit4ClassRunner.class)注解自动创建容器-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.0.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>
第二步:使用@RunWith注解替换原有运行器
/**
 * 使用Junit单元测试,测试我们的配置
 */
@RunWith(SpringJUnit4ClassRunner.class) //使用Junit提供的一个注解把原有的main方法替换了,替换成spring提供的
public class AccountServiceTest {
}
第三步:使用@ContextConfiguration指定spring配置文件的位置
/**
 * 使用Junit单元测试,测试我们的配置
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
}

@ContextConfiguration注解

locations属性:用于指定配置文件的位置。如果是类路径下,需要用 classpath表明

classes属性:用于指定注解的类。当不使用 xml 配置时,需要用此属性指定注解类的位置。

第四步:使用@Autowired给测试类中的变量注入数据
/**
 * 使用Junit单元测试,测试我们的配置
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {

    @Autowired
    private IAccountService as;
    
}

为什么不把测试类配到xml中

在解释这个问题之前,先解除大家的疑虑,配到 XML 中能不能用呢?

答案是肯定的,没问题,可以使用。

那么为什么不采用配置到 xml 中的方式呢?

原因是这样的:

第一:当我们在 xml 中配置了一个 bean,spring 加载配置文件创建容器时,就会创建对象。

第二:测试类只是我们在测试功能时使用,而在项目中它并不参与程序逻辑,也不会解决需求上的问题,所以创建完了,并没有使用。那么存在容器中就会造成资源的浪费。

所以,基于以上两点,我们不应该把测试配置到 xml 文件中。

关于Spring注解和XML的选择问题以及新注解说明

Spring注解和XML的比较

注解的优势

配置简单,维护方便(我们找到类,就相当于找到了对应的配置)。

XML的优势

修改时,不用改源码。不涉及重新编译和部署。

Spring管理Bean方式的比较

在这里插入图片描述

Spring管理对象细节

基于注解的 spring IoC 配置中,bean 对象的特点和基于 XML 配置是一模一样的。

Spring的纯注解配置

写到此处,基于注解的 IoC 配置已经完成,但是大家都发现了一个问题:我们依然离不开 spring 的 xml 配置文件,那么能不能不写这个 bean.xml,所有配置都用注解来实现呢?

当然,同学们也需要注意一下,我们选择哪种配置的原则是简化开发和配置方便,而非追求某种技术。

待改造的问题

我们发现,之所以我们现在离不开 xml 配置文件,是因为我们有一句很关键的配置:

<!--告知spring在创建容器时要扫描的包,配置所需要的标签不是在beans的约束中,而是在一个名称为context名称空间和约束中,如上-->
<!--此时就会扫描com.itheima下所有类的注解-->
<context:component-scan base-package="com.itheima"></context:component-scan>

如果他要也能用注解配置,那么我们就离脱离 xml 文件又进了一步。

另外,数据源和 JdbcTemplate 的配置也需要靠注解来实现。

<!--配置QueryRunner scope="prototype"配置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="root"></property>
</bean>

新注解说明

@Configuration

作用:指定当前类是一个配置类
细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写
属性:
value:用于指定配置类的字节码

示例代码

/**
 * 该类是一个配置类,它的作用和bean.xml是一样的
 */
@Configuration
public class SpringConfiguration {
}

注意:我们已经把配置文件用类来代替了,但是如何配置创建容器时要扫描的包呢?请看下一个注解。

@ComponentScan

作用:用于通过注解指定spring在创建容器时要扫描的包
属性:
value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包
我们使用了此注解就等同于在xml中配置了:
<context:component-scan base-package="com.itheima"></context:component-scan>

示例代码

/**
 * 该类是一个配置类,它的作用和bean.xml是一样的
 */
@Configuration
@ComponentScan("com.itheima") //注解属性只有一个且value,value可省略,是数组,但值只有一个时,{}可省略
public class SpringConfiguration {
}

注意:我们已经配置好了要扫描的包,但是数据源和 JdbcTemplate 对象如何从配置文件中移除呢?请看下一个注解。

@Bean

作用:用于把当前方法的返回值作为bean对象存入spring的IOC容器中
属性:
name:用于指定bean的id,当不写时,默认值是当前方法的名称
细节:
当我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象查找的方式和Autowired注解的作用是一样的

示例代码

package config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import javax.sql.DataSource;

/**
 * 和spring连接数据库相关的配置类
 */
public class JdbcConfig {

    /**
     * 用于创建一个QueryRunner对象
     * 等同于:
     * <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
     *         <!--注入数据源-->
     *         <constructor-arg name="ds" ref="dataSource"></constructor-arg>
     * </bean>
     * @param dataSource
     * @return
     */
    @Bean(name = "runner")
    @Scope("prototype")
    //Qualifier在给类成员注入时,必须和Autowired结合使用,但在给方法参数注入时,可直接使用
    public QueryRunner createQueryRunner(DataSource dataSource) {
        return new QueryRunner(dataSource);
    }

    /**
     * 创建数据源对象
     * 等同于:
     * <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?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8"></property>
     *         <property name="user" value="root"></property>
     *         <property name="password" value="root"></property>
     * </bean>
     * @return
     */
    @Bean(name = "dataSource")
    public DataSource createDataSource() {
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass("com.mysql.jdbc.Driver");
            ds.setJdbcUrl("jdbc:mysql://localhost:3306/eesy?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
            ds.setUser("root");
            ds.setPassword("root");
            return ds;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    
}

注意:我们已经把数据源和 QueryRunner 从配置文件中移除了,此时可以删除 bean.xml 了。但是由于没有了配置文件,创建数据源的配置又都写死在类中了。如何把它们配置出来呢?请看下一个注解。

@PropertySource

作用:用于指定properties文件的位置
属性:
value[]:指定文件的名称和路径
关键字:classpath:表示类路径下,有包也需要写

示例代码

package config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
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.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;
import javax.sql.DataSource;

/**
 * 和spring连接数据库相关的配置类
 */
//.properties文件一运行都部署到工作空间里class的类路径在,故需加classpath:
@PropertySource("classpath:jdbcConfig.properties")
public class JdbcConfig {
    
    @Value("${jdbc.driver}")
    private String driver;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    /**
     * 创建数据源对象
     * 等同于:
     * <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="root"></property>
     * </bean>
     * @return
     */
    @Bean(name = "dataSource")
    public DataSource createDataSource() {
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    
}

jdbc.properties文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/eesy?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
jdbc.username=root
jdbc.password=root

注意:此时我们已经有了两个配置类,但是他们还没有关系。如何建立他们的关系呢?请看下一个注解。

@Import:

作用:用于导入其他配置类
属性:
value[]:用于指定其他配置类的字节码
细节:当我们使用Import的注解之后,有Import注解的类就是父配置类,而导入的都是子配置类

示例代码

/**
 * 该类是一个配置类,它的作用和bean.xml是一样的
 */
@Configuration
@ComponentScan("com.itheima") //注解属性只有一个且value,value可省略,是数组,但值只有一个时,{}可省略
@Import(JdbcConfig.class)
public class SpringConfiguration {
}

注意:我们已经把要配置的都配置好了,但是新的问题产生了,由于没有配置文件了,如何获取容器呢?请看下面。

通过注解获取容器

ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);

使用Spring的纯注解配置实现账户的CRUD

使用Spring的纯注解配置实现账户的CRUD是将上面使用spring的IoC的实现账户的CRUD改成了基于注解的配置,故需求、技术要求以及环境搭建中的添加jar包和创建数据库和表的操作都是一样的

编写实体类

package com.itheima.domain;

import java.io.Serializable;

/**
 * 账户的实体类
 */
public class Account implements Serializable {

    private Integer id;
    private String name;
    private Float money;
    
}

编写数据源的配置参数jdbcConfig.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/eesy?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
jdbc.username=root
jdbc.password=root

编写数据源的配置类

package config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import javax.sql.DataSource;

/**
 * 和spring连接数据库相关的配置类
 */
@Configuration
@PropertySource("classpath:jdbcConfig.properties")
public class JdbcConfig {
    
    @Value("${jdbc.driver}")
    private String driver;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    /**
     * 用于创建一个QueryRunner对象
     * 等同于:
     * <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
     *         <!--注入数据源-->
     *         <constructor-arg name="ds" ref="dataSource"></constructor-arg>
     * </bean>
     * @param dataSource
     * @return
     */
    @Bean(name = "runner")
    @Scope("prototype")
    //Qualifier在给类成员注入时,必须和Autowired结合使用,但在给方法参数注入时,可直接使用
    public QueryRunner createQueryRunner(@Qualifier("ds2") DataSource dataSource) {
        return new QueryRunner(dataSource);
    }

    /**
     * 创建数据源对象
     * 等同于:
     * <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?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8"></property>
     *         <property name="user" value="root"></property>
     *         <property name="password" value="root"></property>
     * </bean>
     * @return
     */
    @Bean(name = "ds2")
    public DataSource createDataSource() {
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Bean(name = "ds1")
    public DataSource createDataSource1() {
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl("jdbc:mysql://localhost:3306/eesy02");
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

编写持久层

package com.itheima.dao;

import com.itheima.domain.Account;

import java.util.List;

/**
 * 账户的持久层接口
 */
public interface IAccountDao {

    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 查询一个
     * @return
     */
    Account findAccountById(Integer accountId);

    /**
     * 保存
     * @param account
     */
    void saveAccount(Account account);

    /**
     * 更新
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 删除
     * @param acccountId
     */
    void deleteAccount(Integer acccountId);
}

编写持久层实现类

package com.itheima.dao.impl;

import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 账户的持久层实现类
 */
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {

    @Autowired
    private QueryRunner runner;

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

    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);
        }
    }

    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);
        }
    }

    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);
        }
    }

    public void deleteAccount(Integer accountId) {
        try{
            runner.update("delete from account where id=?",accountId);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

编写业务层

package com.itheima.service;

import com.itheima.domain.Account;

import java.util.List;

/**
 * 账户的业务层接口
 */
public interface IAccountService {

    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 查询一个
     * @return
     */
    Account findAccountById(Integer accountId);

    /**
     * 保存
     * @param account
     */
    void saveAccount(Account account);

    /**
     * 更新
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 删除
     * @param acccountId
     */
    void deleteAccount(Integer acccountId);

}

编写业务层实现类

package com.itheima.service.impl;

import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 账户的业务层实现类
 */
@Service("accountService")
public class AccountServiceImpl implements IAccountService{
    
    @Autowired
    private IAccountDao accountDao;

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

    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }

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

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

    public void deleteAccount(Integer acccountId) {
        accountDao.deleteAccount(acccountId);
    }
    
}

编写主配置类

package config;

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

import javax.sql.DataSource;

/**
 * 该类是一个配置类,它的作用和bean.xml是一样的
 */
@Configuration
@ComponentScan("com.itheima") 
@Import(JdbcConfig.class)
public class SpringConfiguration {
}

编写测试类

package com.itheima.test;

import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
import config.JdbcConfig;
import config.SpringConfiguration;
import org.junit.Before;
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 java.util.List;

/**
 * 使用Junit单元测试,测试我们的配置
 */
@RunWith(SpringJUnit4ClassRunner.class) //()里指定一个继承runner的类
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {

    @Autowired
    private IAccountService as;

    @Test
    public void testFindAll(){
        //3.执行方法
        List<Account> accounts = as.findAllAccount();
        for (Account account : accounts) {
            System.out.println(account);
        }
    }

    @Test
    public void testFindOne(){
        //3.执行方法
        Account account = as.findAccountById(1);
        System.out.println(account);
    }

    @Test
    public void testSave(){
        Account account = new Account();
        account.setName("test anno");
        account.setMoney(2000F);
        //3.执行方法
        as.saveAccount(account);
    }

    @Test
    public void testUpdate(){
        //3.执行方法
        Account account = as.findAccountById(5);
        account.setMoney(2500F);
        as.updateAccount(account);
    }

    @Test
    public void testDelete(){
        //3.执行方法
        as.deleteAccount(5);
    }

}

测试QueryRunner是单例或多例

保证多线程安全问题,在数据源的配置类中配置@Scope(“prototype”)是多例则测试结果为false,若配置@Scope(“singleton”)则是单例的测试结果为true,默认是单例。

package com.itheima.test;

import config.SpringConfiguration;
import org.apache.commons.dbutils.QueryRunner;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * 测试QueryRunner是否单例
 */
public class QueryRunnerTest {

    @Test
    public void testQueryRunner() {
        //1.获取容器
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        //2.获取QueryRunner对象
        QueryRunner runner = ac.getBean("runner", QueryRunner.class);
        QueryRunner runner1 = ac.getBean("runner", QueryRunner.class);

        System.out.println(runner == runner1);
    }
}

注意

1、如果配置类作为AnnotationConfigApplicationContext对象创建的参数或者用@Import注解导入的类,@Configuration注解可以不写。

即测试类是ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class,JdbcConfig.class);和用Spring整合Junit的形式就是@ContextConfiguration(classes = {SpringConfiguration.class, JdbcConfig.class}),SpringConfiguration类和JdbcConfig类上面可以不加@Configuration注解

2、@PropertySource(“classpath:jdbcConfig.properties”)该注解写在主配置类或者其他配置类都是可以的。

3、关于主配置类导入其他配置类进行测试的方式有多种,关键是思想,怎么让测试类找到主配置类和其他配置类,配置类里需要配置要扫描的包,所有的需要交给spring的IOC进行管理的对象都必须在包下且配置相应的注解供spring识别。

方式一

把JdbcConfig.class传入ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class,JdbcConfig.class);

用Spring整合Junit的形式就是@ContextConfiguration(classes = {SpringConfiguration.class, JdbcConfig.class}),此时不需要在SpringConfiguration类中的这个注解@Import(JdbcConfig.class)

方式二

在JdbcConfig类上加Configuration注解且配置扫描JdbcConfig类所在的包;

@Configuration
@PropertySource("classpath:jdbcConfig.properties")
public class JdbcConfig {
}
@ComponentScan({"com.itheima","config"})
public class SpringConfiguration {
}
@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值