Spring框架学习02

写在前面

今天主要学习了spring框架中的ioc注解,并且通过实现一个简易的CRUD的方式来巩固了昨天学习的xml配置方法。最后学习了一些关于junit和spring整合的结果。

spring中的ioc注解

 * 曾经XML的配置:
 * <bean id="accountService" class="com.liuge.service.impl.AccountServiceImpl"
 * scope = "" init-method ="" destroy-method="">
 *          <property name="" value="|ref="></property>
 * </bean>
 *
 *
 * 用于创建对象的
 *          他们的作用就和在XML配置文件中编写一个<bean>标签实现的功能是一样的
 * @Componet:
 *          作用:用于把当前类对象存入spring容器中
 *          属性:value:用于指定bean的id值,当我们不写时,它的默认值是当前类名且首字母小写.
 *          Controller:一般用在表现层
 *          Service:一般用于业务层
 *          Repository:一般用于持久层
 *          以上三个注解他们的作用和属性与Component是一模一样的,
 *          他们三个是spring框架为我们提供明确的三层使用的注解,使我们的三层对象更加清晰
 * 用于注入数据的
 *          他们的作用就和在xml配置文件中的bean标签写一个<property>标签的作用是一样的
 *          Autowired:
 *              作用:自动按照类型注入.只要容器中有唯一的bean对象类型和要注入的变量类型匹配,就可以注入成功.
 *                  如果ioc容器中没有任何bean的类型和要注入的变量类型匹配,则报错.
 *                  如果ioc容器中有多个类型匹配时,
 *              出现位置:
 *                  可以是变量上,也可以是方法上.
 *               细节:
 *                  在使用注解注入时,set方法就不是必须的了.
 *            Qualifier:
 *                  作用:在按照类中注入的基础之上再按照名称注入,它在给类成员注入时不能单独使用,但是在给方法参数注入时可以
 *                  属性:
 *                      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:
 *              作用:用于指定初始化方法
 */

可以看到,spring中的IOC注解有很多。我们接下来考虑使用xml和ioc注解的方式来完成一个简单的CRUD案例.

xml+ioc注解方式实现CRUD.

具体的编写CRUD的service,dao等就不再赘述.已经写了很多遍了。这里放一下数据库结构:

下面是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在创建容器时要扫描的包 -->
    <context:component-scan base-package="com.liuge"></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/eesy"></property>
        <property name="user" value="root"></property>
        <property name="password" value="abc456"></property>
    </bean>
</beans>

可以看到,我们这里把自己写的类都用了ioc注解的方式进行了配置,而在bean.xml中配置的都是jar包中带的类。
junit测试方法:

//测试方法很多,这里简单放一个:
   @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);
        }

经过测试,测试通过。这样子我们的ioc注解结合xml的CRUD案例已经实现了.

纯ioc注解的CRUD案例

那我们能不能完全取消掉xml配置文件呢?答案当然是可以的。
这是配置类

/**
 * @ClassName: SpringConfiguration
 * @Description: 该类是一个配置类,它的作用和bean.xml是一样的
 * @author: LiuGe
 * @date: 2020/4/30  1:23
 * Spring中的新注解
 * Configuration
 *      作用:指定当前类是一个配置类
 *      细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该参数可以不写
 * ComponentScan
 *      作用:用于通过注解指定spring在创建容器时要扫描的包
 *      属性:
 *          value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包
 *                我们使用此注解就等同于在xml中配置了
 *     <context:component-scan base-package="com.liuge"></context:component-scan>
 * Bean
 *      作用:用于把当前方法的返回值作为bean对象存入spring的IOC容器中
 *      属性:
 *          name:用于指定bean的id。默认值是当前方法的名称.
 *      细节:
 *          当我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找可用的bean对象
 *          查找的方式和Autowired注解的作用是一样的
 *  Import
 *         作用:用于导入其他的配置类
 *         属性:
 *              value:用于指定其他配置类的字节码.
 *                  当我们使用import注解之后,有import注解的类就是父配置类,而导入的都是子配置类
 * PropertySource
 *      作用:用于指定properties文件的位置
 *      属性:
 *          value:指定文件的名称和路径.
 *                  关键字:classpath:表示类路径下
 */
//@Configuration
@ComponentScan("com.liuge")
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {

}

这是jdbc配置类:

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;

/**
 * @ClassName: JdbcConfig
 * @Description: 和spring连接数据库相关的配置
 * @author: LiuGe
 * @date: 2020/4/30  20:06
 */
//@Configuration
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对象
     * @param dataSource
     * @return
     */
    @Bean(name= "runner")
    @Scope("prototype")
    public QueryRunner createQueryRunner(DataSource dataSource){
        return new QueryRunner(dataSource);
    }

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

    }
}

我们接着用上面的测试方法,可以看到成功了。说明我们的纯ioc注解方式也实现了。

纯ioc注解和xml+ioc注解的选择

我们在上面可以看到,纯ioc注解的方式并不能给我带来预想之中的方便,反而也带来了一些麻烦。因此在个人开发中我们应该尝试使用ioc注解+xml配置的方式。
将我们自己开发的类都用ioc注解,而jar包中的对象都在xml中进行依赖注入。

关于junit的思考

junit是java提供的一个测试工具。但对于测试人员来说,他们可能根本不会写spring框架的相关代码,他们测试可能只是测试代码的可行性和效率。
那我们怎么做到让他们直接就能写测试方法呢?我们想到了Autowired(自动注入),但junit又不处于spring框架内,自然也是用不了spring框架的自动注入的。
但spring早为我们整合好了相应的spring-test类。

使用spring和junit整合。

首先我们要导入jar包:

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

然后我们就可以用ioc注解来改造junit了:

/**
 * @ClassName: AccountServiceTest
 * @Description: 使用Junit单元测试:测试我们的配置
 * @author: LiuGe
 * @date: 2020/4/30  1:05
 * Spring整合Junit配置
 *  1.导入spring整合junit的Jar包(坐标)
 *  2.使用Junit提供的一个注解把原有的main方法替换了,替换成spring提供的
 * @Runwith
 * 3.告知spring的运行器,spring和ioc创建是基于xml还是注解的,并且说明位置.
 * @ContextConfiguration
 *          locations:指定xml文件的位置,加上classpath关键字,表示在类路径下
 *          classes:指定注解类所在地位置
 *  当我们使用spring 5.x版本的时候,要求junit的jar包必须是4.12及以上
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)

后记

在使用idea的maven项目过程中出现了一系列小问题,下篇博客写一写这些小问题的解决方案。

猜你喜欢

转载自www.cnblogs.com/wushenjiang/p/12811654.html