5.2、Spring优化xml配置文件(junit优化及Configuration、ComponentScan、Bean)

1、纯注解完成的查找数据库代码优化

  1. 持久层代码(set,get等自行补充)

    public class Account implements Serializable {
        private Integer id;
        private String name;
        private Float money;
    }
    
    //实现类
    @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 interface IAccountDao {
       List<Account> findAllAccount();
   }

```java
   2. 业务层代码(接口类没写)
   @Service("accountService")
   public class AccountServiceImpl implements IAccountService{
   	@Autowired
       private IAccountDao accountDao;
   
       public List<Account> findAllAccount() {
           return accountDao.findAllAccount();
       }
   }
  1. xml配置文件(前)

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
        
        <context:component-scan base-package="com.itheima"></context:component-scan>
    
        <!--配置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/nba"></property>
            <property name="user" value="root"></property>
            <property name="password" value="root"></property>
        </bean>
    </beans>
    
  2. 测试类

   package com.itheima.test;
   
   import com.itheima.domain.Account;
   import com.itheima.service.IAccountService;
   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(locations = "classpath:bean.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);
           }
       }
   }
   
  1. pom

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.itheima</groupId>
        <artifactId>day02_eesy_02account_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>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>5.0.2.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>commons-dbutils</groupId>
                <artifactId>commons-dbutils</artifactId>
                <version>1.4</version>
            </dependency>
    
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.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>
    

2、关于junit集成spring的注意点

2.1、RunWith注解

替换了原有的运行器,表达为SpringJUnit4ClassRunner.class

2.2、ContextConfiguration注解

若为xml则:

@ContextConfiguration(locations = "classpath:bean.xml")

若为纯注解配置则:

@ContextConfiguration(classes = SpringConfiguration.class)

指定了spring 配置文件的位置

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

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

3、纯注解优化配置文件

​ 基于以上我们发现未优化的部分还有两块,要去除xml的配置文件,那我们可以使用以下注解完成。[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3UYbzntJ-1609943108945)(C:\Users\Microsoft Book\Desktop\snipaste_20210105_212714.png)]

3.1 Configuration

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

​ 根据此类就可以写一个java的基于spring的配置文件,其实该文件就等于xml的配置文件。

3.2 ComponentScan

​ 用于指定 spring 在初始化容器时要扫描的包。作用和在 spring 的 xml 配置文件中的<context:component-scan base-package=“com.chen”/>是一样的

3.3 Bean(写在方法上,创建对象)

​ 该注解只能写在方法上,表明使用此方法创建一个对象,并且放入 spring 容器。以下有一个name属性,他代表的就是bean中的id。

4、优化后得配置文件

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

    @Bean(name = "runner")
    public  QueryRunner getQueryRunner(DataSource ds){
        return new QueryRunner(ds);
    }

    @Bean(name = "ds")
    public DataSource CreateDs(){
        ComboPooledDataSource cpds = new ComboPooledDataSource();
        try {
            cpds.setJdbcUrl("jdbc:mysql://localhost:3306/nba");
            cpds.setDriverClass("com.mysql.jdbc.Driver");
            cpds.setUser("root");
            cpds.setPassword("root");
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        return cpds;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值