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配置文件(前)

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

    
    <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.0modelVersion>
    
        <groupId>com.itheimagroupId>
        <artifactId>day02_eesy_02account_xmliocartifactId>
        <version>1.0-SNAPSHOTversion>
        <packaging>jarpackaging>
    
        <dependencies>
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-contextartifactId>
                <version>5.0.2.RELEASEversion>
            dependency>
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-testartifactId>
                <version>5.0.2.RELEASEversion>
            dependency>
            <dependency>
                <groupId>commons-dbutilsgroupId>
                <artifactId>commons-dbutilsartifactId>
                <version>1.4version>
            dependency>
    
            <dependency>
                <groupId>mysqlgroupId>
                <artifactId>mysql-connector-javaartifactId>
                <version>5.1.6version>
            dependency>
    
            <dependency>
                <groupId>c3p0groupId>
                <artifactId>c3p0artifactId>
                <version>0.9.1.2version>
            dependency>
    
            <dependency>
                <groupId>junitgroupId>
                <artifactId>junitartifactId>
                <version>4.12version>
            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 配置文件中的是一样的

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

你可能感兴趣的:(spring)