Spring基于注解的IOC

1. 基于注解的 IOC 配置

1.1 注解配置和 XML 配置的区别

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

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

1.2 Spring 中 IOC 的常用注解

1.2.1 用于创建对象的注解

  1. 作用

    和在 XML 配置文件中编写一个 <bean> 标签实现的功能是一样的

  2. @Component

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

    • 属性:

      • value:用于指定 bean 的 id 。当我们不写时,它的默认值是当前类名,且首字母改小写。
  3. @Controller:一般用在表现层

  4. @Service:一般用在业务层

  5. @Repository:一般用在持久层

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

1.2.2 用于注入数据的注解

  1. 作用

    和在xml配置文件中的 <bean> 标签中写一个 <property> 标签的作用是一样的

  2. @Autowired

    • 作用:自动按照类型注入。只要容器中有唯一的一个 bean 对象类型和要注入的变量类型匹配,就可以注入成功
      • 如果 ioc 容器中没有任何 bean 的类型和要注入的变量类型匹配,则报错。
      • 如果 Ioc 容器中有多个类型匹配时,按变量名称匹配
    • 出现位置:可以是变量上,也可以是方法上
    • 细节:在使用注解注入时,set 方法就不是必须的了。
  3. @Qualifier

    • 作用:在按照类中注入的基础之上再按照名称注入。它在给类成员注入时不能单独使用。但是在给方法参数注入时可以单独使用。
    • 属性:
      • value:用于指定注入 bean 的 id。
  4. @Resource

    • 作用:直接按照 bean 的 id 注入。它可以独立使用
    • 属性:
      • name:用于指定注入 bean 的 id。
  5. @Value

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

    • 属性:

      • value:用于指定数据的值。它可以使用 spring 中 SpEL (也就是 spring 的 el 表达式)

        SpEL的写法:${表达式}

注意:前三个注解都只能注入其他 bean 类型的数据,而基本类型和 String 类型可以用最后一个注解注入。

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

  1. 作用

    和在 <bean> 标签中使用 <scope> 属性实现的功能是一样的

  2. @Scope

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

1.2.4 和生命周期相关的注解

  1. 作用

    和在 <bean> 标签中使用 <init-method><destroy-methode> 的作用是一样的

  2. PreDestroy

    • 作用:用于指定销毁方法
  3. PostConstruct

    • 作用:用于指定初始化方法

1.3 注解配置的练习

  1. 创建 Maven 的 Java工程,工程信息如下:

    <groupId>com.zt</groupId>
    <artifactId>spring_day02</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    
  2. 添加 Spring 5.0.2 的坐标

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.2.RELEASE</version>
    </dependency>
    
  3. 在 resources 中创建配置文件 bean.xml,告知 spring 在创建容器时要扫描的包

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
    
        <!--告知 spring 在创建容器时要扫描的包,配置所需要的标签不是在 beans 的约束中,而是一个名称为 context 名称空间和约束中-->
        <context:component-scan base-package="com.zt"></context:component-scan>
    
    </beans>
    
  4. 创建持久层接口和实现类

    AccountDao 接口

    public interface AccountDao {
        public void saveAccount();
    }
    

    AccountDaoImpl

    /**
     * 曾经XML的配置:
     * <bean id="accountDao" class="com.zt.dao.impl.AccountDaoImpl"></bean>
     */
    @Repository("accountDao")
    public class AccountDaoImpl implements AccountDao {
        public void saveAccount() {
            System.out.println("保存了账户");
        }
    }
    
  5. 创建业务层接口和实现类

    AccountService 接口

    public interface AccountService {
        /**
         * 模拟保存账户
         */
        public void saveAccount();
    }
    

    AccountServiceImpl

    /**
     * 曾经XML的配置:
     * <bean id="accountService" class="com.zt.service.impl.AccountServiceImpl">
     *     <property name="accountDao" ref="accountDao"></property>
     * </bean>
     */
    @Service("accountService")
    public class AccountServiceImpl implements AccountService {
        @Resource(name="accountDao")
        private AccountDao accountDao;
    
        public void saveAccount() {
            accountDao.saveAccount();
        }
    }
    
  6. 创建表现层

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

2. 账户操作案例

2.1 案例需求

实现对账户的 CRUD 操作

2.2 概要设计

2.2.1 技术选型

  • Mysql 数据库
  • Spring JDBC 工具类
  • Druid 连接池
  • Spring
  • Junit

2.2.2 数据库设计

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

2.3 开发阶段(基于 XML 配置)

  1. 创建数据库环境

    1. 打开 Navicat,新建一个数据库 spring_day02
    2. 创建 account 表(表的结构概要设计中已给出)
  2. 创建 Maven 的 Java工程,工程信息如下:

    <groupId>com.zt</groupId>
    <artifactId>spring_day02_2</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    
  3. 添加依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
    
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
    
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
    
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.9</version>
        </dependency>
    
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>
    </dependencies>
    
    
  4. 创建业务层接口和实现类

    AccountService 接口

    /**
     * 账户的业务层接口
     */
    public interface AccountService {
        /**
         * 查询所有
         * @return
         */
        List<Account> findAllAccount();
    
        /**
         * 查询一个
         * @param id
         * @return
         */
        Account findAccountById(Integer id);
    
        /**
         * 保存操作
         * @param account
         */
        void saveAccount(Account account);
    
        /**
         * 更新操作
         * @param account
         */
        void updateAccount(Account account);
    
        /**
         * 删除操作
         * @param id
         */
        void deleteAccount(Integer id);
    }
    
    

    AccountServiceImpl

    /**
     * 账户业务层实现类
     */
    public class AccountServiceImpl implements AccountService {
    
        private AccountDao accountDao;
    
        public void setAccountDao(AccountDao accountDao) {
            this.accountDao = accountDao;
        }
    
        public List<Account> findAllAccount() {
            return accountDao.findAllAccount();
        }
    
        public Account findAccountById(Integer id) {
            return accountDao.findAccountById(id);
        }
    
        public void saveAccount(Account account) {
            accountDao.saveAccount(account);
        }
    
        public void updateAccount(Account account) {
            accountDao.updateAccount(account);
        }
    
        public void deleteAccount(Integer id) {
            accountDao.deleteAccount(id);
        }
    }
    
    
  5. 创建持久层接口和实现类

    AccountDao 接口

    /**
     * 账户的持久层接口
     */
    public interface AccountDao {
        /**
         * 查询所有
         * @return
         */
        List<Account> findAllAccount();
    
        /**
         * 查询一个
         * @param id
         * @return
         */
        Account findAccountById(Integer id);
    
        /**
         * 保存操作
         * @param account
         */
        void saveAccount(Account account);
    
        /**
         * 更新操作
         * @param account
         */
        void updateAccount(Account account);
    
        /**
         * 删除操作
         * @param id
         */
        void deleteAccount(Integer id);
    }
    
    

    AccountDaoImpl

    /**
     * 账户的持久层实现类
     */
    public class AccountDaoImpl implements AccountDao {
        private JdbcTemplate jdbcTemplate;
    
        public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
            this.jdbcTemplate = jdbcTemplate;
        }
    
        public List<Account> findAllAccount() {
            String sql = "select * from account";
            List<Account> accounts = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Account>(Account.class));
            return accounts;
        }
    
        public Account findAccountById(Integer id) {
            String sql = "select * from account where id = ?";
            Account account = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Account>(Account.class),id);
            return account;
        }
    
        public void saveAccount(Account account) {
            String sql = "insert into account values(null,?,?)";
            jdbcTemplate.update(sql,account.getName(),account.getMoney());
    
        }
    
        public void updateAccount(Account account) {
            String sql = "update account set name = ? and money = ? where id = ?";
            jdbcTemplate.update(sql,account.getName(),account.getMoney(),account.getId());
        }
    
        public void deleteAccount(Integer id) {
            String sql = "delete from account where id = ?";
            jdbcTemplate.update(sql,id);
        }
    }
    
    
  6. 创建实体类

    /**
     * 账户实体类
     */
    public class Account implements Serializable {
        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 +
                    '}';
        }
    }
    
  7. 在 resources 中创建配置文件 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.zt.service.impl.AccountServiceImpl">
            <property name="accountDao" ref="accountDao"></property>
        </bean>
    
        <!--配置 dao 对象-->
        <bean id="accountDao" class="com.zt.dao.impl.AccountDaoImpl">
            <property name="jdbcTemplate" ref="jdbcTemplate"></property>
        </bean>
    
        <!--配置 jdbcTemplate 对象,多例-->
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" scope="prototype">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
    
        <!--配置 dataSource 对象-->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
            <property name="url" value="jdbc:mysql://127.0.0.1:3306/spring_day02"></property>
            <property name="username" value="root"></property>
            <property name="password" value="123456"></property>
            <property name="initialSize" value="5"></property>
            <property name="maxActive" value="10"></property>
            <property name="maxWait" value="3000"></property>
        </bean>
    
    
    </beans>
    
  8. 在 test\java\com\zt\test 包下创建 AccountServiceTest 测试类

    /**
     * 使用 Junit 单元测试
     */
    public class AccountServiceTest {
    
        private ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        private AccountService accountService = applicationContext.getBean("accountService", AccountService.class);
    
        @Test
        public void testFindAll(){
            List<Account> allAccount = accountService.findAllAccount();
            for (Account account : allAccount) {
                System.out.println(account);
            }
        }
    
        @Test
        public void testFindAccountById(){
            Account accountById = accountService.findAccountById(1);
            System.out.println(accountById);
        }
    
        @Test
        public void testSaveAccount(){
            Account account = new Account();
            account.setName("dddd");
            account.setMoney(1000.0);
            accountService.saveAccount(account);
        }
    
        @Test
        public void testUpdateAccount(){
            Account account = new Account();
            account.setId(4);
            account.setName("ddd");
            account.setMoney(800.0);
            accountService.updateAccount(account);
        }
    
        @Test
        public void testDeleteAccount(){
            accountService.deleteAccount(4);
        }
    }
    
    

2.4 开发阶段(基于注解配置)

  1. 创建 Maven 的 Java工程,工程信息如下:

    <groupId>com.zt</groupId>
    <artifactId>spring_day02_3</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    
    
  2. 添加依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
    
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
    
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
    
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.9</version>
        </dependency>
    
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>
    </dependencies>
    
  3. 创建业务层接口和实现类

    AccountService 接口

    /**
     * 账户的业务层接口
     */
    public interface AccountService {
        /**
         * 查询所有
         * @return
         */
        List<Account> findAllAccount();
    
        /**
         * 查询一个
         * @param id
         * @return
         */
        Account findAccountById(Integer id);
    
        /**
         * 保存操作
         * @param account
         */
        void saveAccount(Account account);
    
        /**
         * 更新操作
         * @param account
         */
        void updateAccount(Account account);
    
        /**
         * 删除操作
         * @param id
         */
        void deleteAccount(Integer id);
    }
    
    

    AccountServiceImpl

    /**
     * 账户业务层实现类
     */
    @Service("accountService")
    public class AccountServiceImpl implements AccountService {
    
        @Resource(name="accountDao")
        private AccountDao accountDao;
    
        public List<Account> findAllAccount() {
            return accountDao.findAllAccount();
        }
    
        public Account findAccountById(Integer id) {
            return accountDao.findAccountById(id);
        }
    
        public void saveAccount(Account account) {
            accountDao.saveAccount(account);
        }
    
        public void updateAccount(Account account) {
            accountDao.updateAccount(account);
        }
    
        public void deleteAccount(Integer id) {
            accountDao.deleteAccount(id);
        }
    }
    
    
  4. 创建持久层接口和实现类

    AccountDao 接口

    /**
     * 账户的持久层接口
     */
    public interface AccountDao {
        /**
         * 查询所有
         * @return
         */
        List<Account> findAllAccount();
    
        /**
         * 查询一个
         * @param id
         * @return
         */
        Account findAccountById(Integer id);
    
        /**
         * 保存操作
         * @param account
         */
        void saveAccount(Account account);
    
        /**
         * 更新操作
         * @param account
         */
        void updateAccount(Account account);
    
        /**
         * 删除操作
         * @param id
         */
        void deleteAccount(Integer id);
    }
    
    

    AccountDaoImpl

    /**
     * 账户的持久层实现类
     */
    @Repository("accountDao")
    public class AccountDaoImpl implements AccountDao {
        @Resource(name="jdbcTemplate")
        private JdbcTemplate jdbcTemplate;
    
        public List<Account> findAllAccount() {
            String sql = "select * from account";
            List<Account> accounts = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Account>(Account.class));
            return accounts;
        }
    
        public Account findAccountById(Integer id) {
            String sql = "select * from account where id = ?";
            Account account = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Account>(Account.class),id);
            return account;
        }
    
        public void saveAccount(Account account) {
            String sql = "insert into account values(null,?,?)";
            jdbcTemplate.update(sql,account.getName(),account.getMoney());
    
        }
    
        public void updateAccount(Account account) {
            String sql = "update account set name = ? , money = ? where id = ?";
            jdbcTemplate.update(sql,account.getName(),account.getMoney(),account.getId());
        }
    
        public void deleteAccount(Integer id) {
            String sql = "delete from account where id = ?";
            jdbcTemplate.update(sql,id);
        }
    }
    
    
  5. 创建实体类

    /**
     * 账户实体类
     */
    public class Account implements Serializable {
        private Integer id;
        private String name;
        private Double 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 Double getMoney() {
            return money;
        }
    
        public void setMoney(Double money) {
            this.money = money;
        }
    
        @Override
        public String toString() {
            return "Account{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", money=" + money +
                    '}';
        }
    }
    
    
  6. 在 resources 中创建配置文件 bean.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
    
        <!--告知 spring 在创建容器时要扫描的包,配置所需要的标签不是在 beans 的约束中,而是一个名称为 context 名称空间和约束中-->
        <context:component-scan base-package="com.zt"></context:component-scan>
    
        <!--配置 jdbcTemplate 对象,多例-->
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" scope="prototype">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
    
        <!--配置 dataSource 对象-->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
            <property name="url" value="jdbc:mysql://127.0.0.1:3306/spring_day02"></property>
            <property name="username" value="root"></property>
            <property name="password" value="123456"></property>
            <property name="initialSize" value="5"></property>
            <property name="maxActive" value="10"></property>
            <property name="maxWait" value="3000"></property>
        </bean>
    
    
    </beans>
    
  7. 在 test\java\com\zt\test 包下创建 AccountServiceTest 测试类

    /**
     * 使用 Junit 单元测试
     */
    public class AccountServiceTest {
    
        private ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        private AccountService accountService = applicationContext.getBean("accountService", AccountService.class);
    
        @Test
        public void testFindAll(){
            List<Account> allAccount = accountService.findAllAccount();
            for (Account account : allAccount) {
                System.out.println(account);
            }
        }
    
        @Test
        public void testFindAccountById(){
            Account accountById = accountService.findAccountById(1);
            System.out.println(accountById);
        }
    
        @Test
        public void testSaveAccount(){
            Account account = new Account();
            account.setName("dddd");
            account.setMoney(1000.0);
            accountService.saveAccount(account);
        }
    
        @Test
        public void testUpdateAccount(){
            Account account = new Account();
            account.setId(4);
            account.setName("ddd");
            account.setMoney(800.0);
            accountService.updateAccount(account);
        }
    
        @Test
        public void testDeleteAccount(){
            accountService.deleteAccount(4);
        }
    }
    
    

3. 纯注解配置

3.1 待改造的问题

基于注解的 IOC 配置已经完成,但还存在一个问题:我们依然离不开 spring 的 xml 配置文件,那么能不能不写这个 bean.xml,所有配置都用注解来实现呢?

3.2 新注解的使用

3.2.1 @Configuration

  1. 作用

    指定当前类是一个配置类(相当于代替了 xml 配置文件)

  2. 属性

    • value:用于指定配置类的字节码
  3. 实例

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

3.2.2 @ComponentScan

  1. 作用

    用于指定在创建容器时要扫描的包。作用和 xml 配置文件中的: <context:component-scan base-package="com.zt"/> 是一样的。

  2. 属性

    • basePackages:用于指定要扫描的包。
  3. 实例

    @Configuration
    @ComponentScan("com.zt")
    public class SpringConfiguration {
    
    }
    

3.2.3 @Bean

  1. 作用

    该注解只能写在方法上,表明把当前方法的返回值作为 bean 对象存入 spring 的 IOC 容器中

  2. 属性

    • name:指定 bean 的 id,当不写时默认是当前方法的名称
  3. 实例

    @Configuration
    @ComponentScan("com.zt")
    public class SpringConfiguration {
        @Bean("jdbcTemplate")
        public JdbcTemplate createJdbcTemplate(DataSource dataSource){
            return new JdbcTemplate(dataSource);
        }
    }
    

3.2.4 @PropertySource

  1. 作用

    用于加载 .properties 文件中的配置。例如我们配置数据源时,可以把连接数据库的信息写到 properties 配置文件中,就可以使用此注解指定 properties 配置文件的位置。

  2. 属性

    • value[]:用于指定 properties 文件位置。如果是在类路径下,需要写上 classpath
  3. 实例

    @Configuration
    @ComponentScan("com.zt")
    @PropertySource("classpath:druid.properties")
    public class SpringConfiguration {
        @Value("${driverClassName}")
        private String driverClassName;
        @Value("${url}")
        private String url;
        @Value("${name}")
        private String name;
        @Value("${password}")
        private String password;
        @Value("${initialSize}")
        private int initialSize;
        @Value("${maxActive}")
        private int maxActive;
        @Value("${maxWait}")
        private int maxWait;
    
        @Bean("jdbcTemplate")
        @Scope("prototype")
        public JdbcTemplate createJdbcTemplate(DataSource dataSource){
            return new JdbcTemplate(dataSource);
        }
    
        @Bean("dataSource")
        public DataSource createDataSource(){
            DruidDataSource druidDataSource = new DruidDataSource();
            druidDataSource.setDriverClassName(driverClassName);
            druidDataSource.setUrl(url);
            druidDataSource.setUsername(name);
            druidDataSource.setPassword(password);
            druidDataSource.setInitialSize(initialSize);
            druidDataSource.setMaxActive(maxActive);
            druidDataSource.setMaxWait(maxWait);
    
            return druidDataSource;
        }
    
    
    }
    
    

3.2.5 @Import

  1. 作用

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

  2. 属性

    • value[]:用于指定其他配置类的字节码。
  3. 实例

    /**
     * 该类是一个配置类,它的作用和 bean.xml 是一样的
     */
    @Configuration
    @ComponentScan("com.zt")
    @PropertySource("classpath:druid.properties")
    @Import(JdbcConfig.class)
    public class SpringConfiguration {
    
    }
    
    /**
     * 和spring连接数据库相关的配置类
     */
    public class JdbcConfig {
        @Value("${driverClassName}")
        private String driverClassName;
        @Value("${url}")
        private String url;
        @Value("${name}")
        private String name;
        @Value("${password}")
        private String password;
        @Value("${initialSize}")
        private int initialSize;
        @Value("${maxActive}")
        private int maxActive;
        @Value("${maxWait}")
        private int maxWait;
    
        @Bean("jdbcTemplate")
        @Scope("prototype")
        public JdbcTemplate createJdbcTemplate(DataSource dataSource){
            return new JdbcTemplate(dataSource);
        }
    
        @Bean("dataSource")
        public DataSource createDataSource(){
            DruidDataSource druidDataSource = new DruidDataSource();
            druidDataSource.setDriverClassName(driverClassName);
            druidDataSource.setUrl(url);
            druidDataSource.setUsername(name);
            druidDataSource.setPassword(password);
            druidDataSource.setInitialSize(initialSize);
            druidDataSource.setMaxActive(maxActive);
            druidDataSource.setMaxWait(maxWait);
    
            return druidDataSource;
        }
    
    }
    
    

3.2.6 通过注解获取容器

ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfiguration.class);

4. Spring 整合 Junit

4.1 待改造的问题

在测试类中还是有以下两行代码:

private ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfiguration.class);
private AccountService accountService = applicationContext.getBean("accountService", AccountService.class);

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

4.2 解决问题分析

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

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

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

4.3 配置步骤

4.3.1 导入 Spring 整合 Junit 的 jar 包

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.0.2.RELEASE</version>
</dependency>
<!--当我们使用 spring 5.x 版本的时候,junit 要求 4.12 及更高版本-->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

4.3.2 使用 @RunWith 注解替换原有运行器

/**
 * 使用 Junit 单元测试
 */
@RunWith(SpringJUnit4ClassRunner.class)
public class AccountServiceTest

4.3.3 使用 @ContextConfiguration 指定 spring 配置的类型和位置

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
// @ContextConfiguration(locations= {"classpath:bean.xml"})
public class AccountServiceTest
  • locations 属性:用于指定配置文件的位置。如果是类路径下,需要用 classpath:表明
  • classes 属性:用于指定注解的类。当不使用 xml 配置时,需要用此属性指定注解类的位置。

4.3.4 使用 @Autowired 给测试类中的变量注入数据

/**
 * 使用 Junit 单元测试
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
    @Autowired
    private AccountService accountService;
发布了64 篇原创文章 · 获赞 20 · 访问量 6504

猜你喜欢

转载自blog.csdn.net/bm1998/article/details/100718263