Spring基础(2)——Spring中基于注解的IOC

目录

1. Spring中的常用注解

1.1 用于创建对象的注解

1.2 用于注入数据的注解

1.3 用于改变作用范围的注解

1.4 和生命周期相关的注解

1.5 关于 Spring 注解和 XML 的选择问题

2.Spring的IOC案例

3.Spring的新注解

4.Spring整合junit

5.SpringIOC总结


1. Spring中的常用注解

注解配置和xml配置要实现的功能都是一样的,都要降低程序的耦合,只是配置的形式不一样

xml中配置示例:

<bean id="accountDao" class="cn.cqu.dao.impl.AccountDaoImpl" scope="" init-method="" destroy-method="">
        <property name= "" value="" | ref=""></property>
</bean>

注解分类:

  • 1.用于创建对象的注解
    • 它们的作用就和在xml中编写一个bean标签是一样的
  • 2.用于注入数据的注解
    • 它们的作用就和在xml中bean标签中写一个property标签是一样的
  • 3.用于改变作用范围的注解
    • 它们的作用就和在xml中bean标签中使用scope属性实现的功能是一样的
  • 4.和生命周期相关的注解
    • 它们的作用就和在bean标签中使用init-method和destroy-method属性是一样的

1.1 用于创建对象的注解

  • 相当于:<bean id="" class="">

(1)@Component

作用:

  • 用于把当前类对象存入Spring容器中,相当于在 xml 中配置一个 bean

属性:

  • value:用于指定bean的id,当我们不写时,它的默认值是当前类名且首字母改小写
    • 如果注解中有一个属性,且这个属性是value时,可以省略value=,即一个省略属性的值,就是value的值

示例:

对于注解配置,我们需要修改配置文件xml

查找约束文件

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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <!--告知spring在创建容器时要扫描的包,配置所需要的标签不是在beans中,
        而是一个名称为context的名称空间和约束中

        添加如下配置之后,就会扫描cn.cqu包及其子包下所有的注解
    -->
    <context:component-scan base-package="cn.cqu"></context:component-scan>
</beans>

IAccountDao.java

package cn.cqu.dao;

/**
 * 账户的持久层接口
 */
public interface IAccountDao {
    /**
     *模拟保存账户
     */
    void saveAccount();
}

AccountDaoImpl.java

package cn.cqu.dao.impl;

import cn.cqu.dao.IAccountDao;
import org.springframework.stereotype.Component;

/**
 * 账户的持久层实现类
 *
 *<bean id="accountDao" class="cn.cqu.dao.impl.AccountDaoImpl"
 *scope="" init-method="" destroy-method="">
 *  <property name= "" value="" | ref=""></property>
 * </bean>
 */


@Component("accountDao")
public class AccountDaoImpl implements IAccountDao {

    public void saveAccount() {
        System.out.println("保存了账户");
    }
}

Client.java

package cn.cqu.ui;

import cn.cqu.dao.IAccountDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 获取spring的IOC核心容器,并根据id获取对象
 */
public class Client {
    public static void main(String[] args) {
        //1.获取核心容器对象
        ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
        //2.根据id获取bean对象
        IAccountDao dao = ac.getBean("accountDao",IAccountDao.class);

        System.out.println(dao);
    }
}

(2)@Controller

  • 一般用于控制层

(3)@Service

  • 一般用于服务层

(4)@Repository

  • 一般用于持久层

以上三个注解它们的作用和属性和@Component是一模一样的

它们三个是spring框架为我们提供明确的三层使用的注解,使我们的三层对象更加清晰

细节:如果注解中有且只有一个属性要赋值时,且名称是 value,value 在赋值是可以不写。

1.2 用于注入数据的注解

相当于:

  • <property name="" ref="">
  • <property name="" value="">

(1)@Autowired

出现位置:

  • 可以是成员变量上,也可以是方法上

细节:

  • 在使用注解注入时,set方法就不是必须的了

作用:

  • 自动按照类型注入,只要容器中有一个唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功
  • 如果IOC容器中没有任何bean的类型和要注入的变量类型匹配,则报错

示例代码:

package cn.cqu.dao;

/**
 * 账户的持久层接口
 */
public interface IAccountDao {
    /**
     *模拟保存账户
     */
    void saveAccount();
}
package cn.cqu.dao.impl;

import cn.cqu.dao.IAccountDao;
import org.springframework.stereotype.Component;

/**
 * 账户的持久层实现类
 *
 */

@Component("accountDao")
public class AccountDaoImpl {//implements IAccountDao 

    public void saveAccount() {
        System.out.println("保存了账户");
    }
}

注意此处我们对implements IAccountDao进行了注释,即AccountDaoImpl不是IAccountDao类型了

package cn.cqu.service;

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

    void saveAccount();
}
package cn.cqu.service.impl;

import cn.cqu.dao.IAccountDao;
import cn.cqu.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


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

    @Autowired
    private IAccountDao accountDao;

    @Override
    public void saveAccount() {
        accountDao.saveAccount();
    }
}
package cn.cqu.ui;

import cn.cqu.service.IAccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 获取spring的IOC核心容器,并根据id获取对象
 */
public class Client {
    public static void main(String[] args) {
        //1.获取核心容器对象
        ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
        //2.根据id获取bean对象
        IAccountService as = ac.getBean("accountService",IAccountService.class);

        as.saveAccount();
    }
}

取消上述注释,成功运行

  • 如果有多个类型匹配时,它先按照类型找到满足该类型的几个Object,然后根据变量名和key去匹配,如果在key中找不到与变量名匹配的,就报错

示例代码:

package cn.cqu.dao;

/**
 * 账户的持久层接口
 */
public interface IAccountDao {
    /**
     *模拟保存账户
     */
    void saveAccount();
}
package cn.cqu.dao.impl;

import cn.cqu.dao.IAccountDao;
import org.springframework.stereotype.Component;

/**
 * 账户的持久层实现类
 *
 */

@Component("accountDao1")
public class AccountDaoImpl1 implements IAccountDao{

    public void saveAccount() {
        System.out.println("保存了账户1111111");
    }
}
package cn.cqu.dao.impl;

import cn.cqu.dao.IAccountDao;
import org.springframework.stereotype.Component;

/**
 * 账户的持久层实现类
 *
 */

@Component("accountDao2")
public class AccountDaoImpl2 implements IAccountDao{

    public void saveAccount() {
        System.out.println("保存了账户2222222");
    }
}
package cn.cqu.service;

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

    void saveAccount();
}
package cn.cqu.service.impl;

import cn.cqu.dao.IAccountDao;
import cn.cqu.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


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

    @Autowired
    private IAccountDao accountDao;

    @Override
    public void saveAccount() {
        accountDao.saveAccount();
    }
}
package cn.cqu.ui;

import cn.cqu.service.IAccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 获取spring的IOC核心容器,并根据id获取对象
 */
public class Client {
    public static void main(String[] args) {
        //1.获取核心容器对象
        ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
        //2.根据id获取bean对象
        IAccountService as = ac.getBean("accountService",IAccountService.class);

        as.saveAccount();
    }
}

注意此时类AccountServiceImpl中仍然是

修改为,运行结果如下

修改为,运行结果如下

通过以上可以发现当有多个类型需要匹配时,我们需要修改属性变量名,但是通过以下注解@Qualifier与@Autowired我们就可以避免修改变量名

(2)Qualifier

作用:

  • 按照类型注入的基础上再按照名称Qualifier中value值注入
  • 它在给类成员注入时,不能单独使用,但是在给方法参数注入时可以

属性:

  • value:用于指定注入bean的id

注意:

  • @Qualifier必须和@Autowired一起使用

示例:

上述代码中,我们仍然使用accountDao,当加入注解@Qualifier

第一种:

运行结果:

第二种:

运行结果:

(3)Resource

作用:

  • 直接按照bean的id注入,它可以独立使用
  • Resource可以直接指定bean的id,作用相当于@Qualifier必须和@Autowired一起使用的作用

属性:

  • name:用于指定bean的id

示例:

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

另外,集合类型的注入只能通过XML来实现

(4)@Value

作用:

  • 用于注入基本类型和String类型的数据

属性:

  • value:用于指定数据的值,它可以使用Spring中的SpEL(即Spring的EL表达式)
    • SpEL写法:${表达式}

1.3 用于改变作用范围的注解

相当于:<bean id="" class="" scope="">

Scope

作用:

  • 用于指定bean的作用范围

属性:

  • value:指定范围的取值
    • 常用取值:singleton、prototype
    • 当我们不指定,默认情况下也是单例的

示例:

对上述代码中main方法中做如下修改

package cn.cqu.ui;

import cn.cqu.service.IAccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 获取spring的IOC核心容器,并根据id获取对象
 */
public class Client {
    public static void main(String[] args) {
        //1.获取核心容器对象
        ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
        //2.根据id获取bean对象
        IAccountService as01 = ac.getBean("accountService",IAccountService.class);
        IAccountService as02 = ac.getBean("accountService",IAccountService.class);

        System.out.println(as01==as02);
    }
}

当我们使用@Scope注解设置它的value为prototype时

1.4 和生命周期相关的注解

相当于:<bean id="" class="" init-method="" destroy-method="" />

(1)Predestroy

作用:

  • 用于指定销毁方法

(2)PostConstruct

作用:

  • 用于指定初始化方法

示例代码:

修改上述代码中AccountServiceImpl如下

package cn.cqu.service.impl;

import cn.cqu.dao.IAccountDao;
import cn.cqu.service.IAccountService;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

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

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

    @Resource(name="accountDao2")
    private IAccountDao accountDao;

    @Override
    public void saveAccount() {
        accountDao.saveAccount();
    }

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

修改main如下

package cn.cqu.ui;

import cn.cqu.service.IAccountService;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 获取spring的IOC核心容器,并根据id获取对象
 */
public class Client {
    public static void main(String[] args) {
        //1.获取核心容器对象
        ClassPathXmlApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
        //2.根据id获取bean对象
        IAccountService as = ac.getBean("accountService",IAccountService.class);
        
        as.saveAccount();
        ac.close();
    }
}

运行结果:

1.5 关于 Spring 注解和 XML 的选择问题

注解的优势:

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

XML 的优势:

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

Spring 管理 Bean 方式的比较:

2.Spring的IOC案例

创建maven项目

导入依赖

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>cn.cqu</groupId>
    <artifactId>xmlIOC</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>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>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

</project>

创建数据库

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

Account.java

package cn.cqu.domain;

public class Account {
    private Integer id;
    private String name;
    private float money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer 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 +
                '}';
    }
}

IAccountDao.java

package cn.cqu.dao;

import cn.cqu.domain.Account;

import java.util.List;

/**
 * 账户的持久层接口
 */
public interface IAccountDao {
    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();

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

    /**
     * 插入
     * @param account
     */
    void saveAccount(Account account);

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

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

AccountDaoImpl.java

package cn.cqu.dao.impl;

import cn.cqu.dao.IAccountDao;
import cn.cqu.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 QueryRunner getRunner() {
        return 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 findById(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);
        }
    }
}

IAccountService.java

package cn.cqu.service;

import cn.cqu.domain.Account;

import java.util.List;

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

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

    /**
     * 插入
     * @param account
     */
    void saveAccount(Account account);

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

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

}

AccountServiceImpl.java

package cn.cqu.service.impl;

import cn.cqu.domain.Account;
import cn.cqu.service.IAccountService;
import cn.cqu.dao.IAccountDao;
import java.util.List;

public class AccountServiceImpl implements IAccountService {

    private IAccountDao dao;

    public IAccountDao getDao() {
        return dao;
    }

    public void setDao(IAccountDao dao) {
        this.dao = dao;
    }

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

    public Account findById(Integer accountId) {
        return dao.findById(accountId);
    }

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

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

    public void deleteAccount(Integer accountId) {
        dao.deleteAccount(accountId);
    }
}

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">
    <!--  配置业务层对象  -->
    <bean id="accountService" class="cn.cqu.service.impl.AccountServiceImpl">
        <!--    使用set方法注入dao    -->
        <property name="dao" ref="accountDao"></property>
    </bean>


    <!--  配置Dao对象  -->
    <bean id="accountDao" class="cn.cqu.dao.impl.AccountDaoImpl">
        <property name="runner" ref="runner"></property>
    </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/mydb"></property>
        <property name="user" value="root"></property>
        <property name="password" value=""></property>
    </bean>

</beans>

AccountServiceTest.java

package cn.cqu.test;

import cn.cqu.domain.Account;
import cn.cqu.service.IAccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 * 使用Junit单元测试:测试我们的配置
 */
public class AccountServiceTest {
    @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 testFindById()
    {
        //1.获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        IAccountService as = ac.getBean("accountService",IAccountService.class);
        //3.执行方法
        Account account = as.findById(1);
        System.out.println(account);
    }


    @Test
    public void testSaveAccount()
    {
        Account account =new Account();
        account.setName("testFindById");
        account.setMoney(1314);
        //1.获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        IAccountService as = ac.getBean("accountService",IAccountService.class);
        //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.findById(1);
        account.setMoney(234);
        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(3);
    }

}

使用注解对上述部分代码进行改造

AccountDaoImpl.java

package cn.cqu.dao.impl;

import cn.cqu.dao.IAccountDao;
import cn.cqu.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 findById(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);
        }
    }
}

AccountServiceImpl.java

package cn.cqu.service.impl;

import cn.cqu.domain.Account;
import cn.cqu.service.IAccountService;
import cn.cqu.dao.IAccountDao;
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 dao;

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

    public Account findById(Integer accountId) {
        return dao.findById(accountId);
    }

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

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

    public void deleteAccount(Integer accountId) {
        dao.deleteAccount(accountId);
    }
}

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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <!--告知spring要在创建容器时要扫描的包-->
    <context:component-scan base-package="cn.cqu"></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/mydb"></property>
        <property name="user" value="root"></property>
        <property name="password" value=""></property>
    </bean>

</beans>

运行结果同上

3.Spring的新注解

我们依然离不开 spring xml 配置文件,那么能不能不写这个 bean.xml,所有配置都用注解来实现呢?

我们发现,之所以我们现在离不开 xml 配置文件,是因为:

  • 原因1:
    • <!-- 告知spring框架在,读取配置文件,创建容器时,扫描注解,依据注解创建对象,并存入容器中 -->
    • <context:component-scan base-package="com.itheima"></context:component-scan>
    • 如果他要也能用注解配置,那么我们就离脱离 xml 文件又进了一步。
  • 原因2:
    • 数据源和 QueryRunner的配置也需要靠注解来实现。
    • 因为QueryRunner是dbutils下的jar包,我们想给它加注解是加不了的
    • dataSource也是同样的道理

1.首先对如下进行注解改造

创建一个专门的类,大致如下

package cn.cqu.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * 此类的类名和它所在包名由自己命名均可
 *
 * 该类是一个配置类,它的作用和bean.xml是一样的
 */

@Configuration
@ComponentScan(basePackages = "cn.cqu")
public class SpringConfiguration {


}

(1) @Configuration

作用:

  • 用于指定当前类是一个 spring 配置类,当创建容器时会从该 类上加载注解。获取容器时需要使用
  • AnnotationApplicationContext(@Configuration注解的类.class)

属性:

  • value:用于指定配置类的字节码

细节:

  • 当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写

(2)@ComponentScan或@ComponentScans

作用:

  • @ComponentScan用于指定一个通过注解指定Spring在创建容器时要扫描的包
  • @ComponentScans用于指定多个通过注解指定Spring在创建容器时要扫描的包

属性:

  • value或basePackages:用于指定创建容器时要扫描的包

我们使用此注解就等同于在bean.xml中配置了

2.接下来我们对如下进行改造

其实以上配置有两步:

  • 1.创建QueryRunner对象
  • 2.存入Sping的IOC容器中

在该类中添加创建QueryRunner对象的方法,即完成上述的第一步创建QueryRunner对象

使用下面的Bean完成第二步

(3)@Bean

作用:

  • 用于把当前方法的返回值作为bean对象存入Spring的IOC容器中

属性:

  • name:用于指定bean的id,当不写时是当前方法的名称

细节:

  • 当我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象,查找的方式和Autowired注解的作用是一样的
  • 但是如果参数中的类型有多个匹配时,我们同样可以在参数前面加@Qualifer,先根据类型匹配,当有多个类型匹配的时候,根据Qualifer中的value的值来匹配

同样我们也可以使用@Scope来指定作用范围

(4)@Import

作用:

  • 用于导入其他的配置类
  • 通过这种方法,可以将配置写在多个类当中,而设置一个主配置类,然后通过注解@Import将其他的配置类导入到主配置类中聚合在一起相当于一个bean.xml

属性:

  • value:用于指定其他配置类的字节码

当我们使用Import之后,有Import注解的类就是主配置类或父配置类,而导入的都是子配置类

同时它也支持并列的配置关系,我们只需要在使用AnnotationConfigApplicationContext创建容器时,将多个配置类的字节码都作为它的参数

如果像如下那么写的话,就又把它写死了

我们可以写为它专门写一个配置文件jdbcConfig.properties

(5)@PropertySource

作用:

  • 用于指定properties文件的位置

属性:

  • value:指定文件的名称和路径
    • 关键字:classpath,表示类路径下

然后在JdbcConfiguration类中添加四个属性并为它们注入值(通过EL表达式)

上述最终的配置类代码如下,其他业务类都与2中的案例相同

jdbcConfig.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mydb
jdbc.user=root
jdbc.password=

JdbcConfiguration.java

package config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
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;

@Configuration   //如果在AnnotationConfigApplicationContext中传入了JdbcConfiguration.class就可以省略,否则必须写
public class JdbcConfiguration {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.user}")
    private String user;
    @Value("${jdbc.password}")
    private String password;

    /**
     * 用于创建QueryRunner对象
     */
    @Bean(name = "runner")
    public QueryRunner createQueryRunner(DataSource dataSource){
        return new QueryRunner(dataSource);
    }

    /**
     * 用于创建数据源对象
     * @return
     */
    @Bean(name = "dataSource")
    @Scope("prototype")
    public DataSource createDataSource(){
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(user);
            ds.setPassword(password);
            return ds;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}

SpringConfiguration.java

package config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;


/**
 * 此类的类名和它所在包名由自己命名均可
 *
 * 该类是一个配置类,它的作用和bean.xml是一样的
 */

//@Configuration   由于在测试类中使用的时候传入的是配置类的class文件,此处可以省略
@ComponentScan(basePackages = "cn.cqu")    //扫描包cn.cqu
@Import(JdbcConfiguration.class)           //导入JdbcConfiguration类
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {

}

测试类:

package cn.cqu.test;

import config.JdbcConfiguration;
import config.SpringConfiguration;
import cn.cqu.domain.Account;
import cn.cqu.service.IAccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.util.List;

/**
 * 使用Junit单元测试:测试我们的配置
 */
public class AccountServiceTest {
    @Test
    public void testFindAll()
    {
        //1.获取容器
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class,JdbcConfiguration.class);
        //2.得到业务层对象
        IAccountService as = ac.getBean("accountService",IAccountService.class);
        //3.执行方法
        List<Account> accounts = as.findAllAccount();
        for (Account account:accounts)
        {
            System.out.println(account);
        }
    }

}

4.Spring整合junit

对上述Spring整合junit问题分析:

  • 当我们写多个测试方法的时候,以下代码是重复的

于是我们想到将它定义为属性,在@Before注解的方法(在执行每个@Test的方法执行前,都会先执行此方法中的代码)中执行

package cn.cqu.test;

import config.JdbcConfiguration;
import config.SpringConfiguration;
import cn.cqu.domain.Account;
import cn.cqu.service.IAccountService;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.util.List;

/**
 * 使用Junit单元测试:测试我们的配置
 */
public class AccountServiceTest {
    
    private ApplicationContext ac;
    
    private IAccountService as;
    
    @Before
    public void init(){
        //1.获取容器
        ac = new AnnotationConfigApplicationContext(SpringConfiguration.class,JdbcConfiguration.class);
        //2.得到业务层对象
        as = ac.getBean("accountService",IAccountService.class);
    }
    
    @Test
    public void testFindAll()
    {
        //3.执行方法
        List<Account> accounts = as.findAllAccount();
        for (Account account:accounts)
        {
            System.out.println(account);
        }
    }

}

通过以上的方式重复的问题倒是解决了,但是还有以下问题:

  • 在实际的开发中,开发和测试是不同的人员,开发的人员使用Spring框架懂Spring,但是测试人员不一定要懂,而上述代码的写法就要求测试人员也要懂Spring框架

我们立马会想到,Spring是可以通过@Autowired来自动注入的,但是我们直接这样加注解

package cn.cqu.test;

import config.JdbcConfiguration;
import config.SpringConfiguration;
import cn.cqu.domain.Account;
import cn.cqu.service.IAccountService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;

/**
 * 使用Junit单元测试:测试我们的配置
 */
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);
        }
    }

}

但是运行时结果如下,出现空指针异常

上述原因分析:

  • 应用程序的入口是main方法,但是junit单元测试中,没有main方法也能执行,原因如下:
    • junit集成了main方法,它在
    • 该方法会判断当前测试类中哪些方法有@Test注解,如果有,junit就会让该方法执行
  • 但是junit本身的main方法在执行的时候不会管我们是否用了Spring框架,即在执行测试方法时,Spring不知道我们是否使用Spring框架,所以也不会为我们读取配置文件/配置类来为我们创建Spring核心容器
  • 所以当测试方法执行时,没有IOC容器,就算写了@Autowired也无法完成注入

基于以上,我们需要使用Spring整合junit进行配置,将原本的不能加载容器的main方法换成能加载容器的main方法,从而实现创建容器,步骤如下:

  • 1.导入Spring整合junit的jar包
  • 2.使用junit提供的一个注解把原有的main方法给替换掉,替换成spring提供的————@RunWith,替换为SpringJunit4ClassRunner(继承了Runner)这个类的字节码
  • 3.告知Spring的运行器,Spring的IOC是基于注解的还是基于xml的,并且说明位置——@ContextConfiguration
    • locations:指定xml的位置,加上classpath关键字表示在类路径下
    • classes:指定注解类所在位置(使用的是类的字节码)

注意:当我们在使用spring5.x版本的时候,junit的版本要求是4.12及以上

最终该测试类代码:

package cn.cqu.test;

import cn.cqu.domain.Account;
import cn.cqu.service.IAccountService;
import config.SpringConfiguration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;

/**
 * 使用Junit单元测试:测试我们的配置
 */

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
//@ContextConfiguration(locations = "classpath:bean.xml")   xml配置示例
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);
        }
    }

}

此时同样成功执行

5.SpringIOC总结

对Spring依赖总结:

  • 变化集中转移到配置(配置文件或注解)中
  • Spring框架内部依赖于配置
  • 自定义类依赖于不变(String)
  • 从而编译时依赖转运行时依赖,降低耦合
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值