主流框架二:Spring(3)Spring基于注解的IOC和案例分析

一、案例使用XML方式实现单表的CRUD操作

持久层技术的选择:dbutils

1、案例准备:

(1)导入包坐标

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

(2)编写domain实体类

/**
 * 账户的实体类
 */
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 +
                '}';
    }
}

(3)编写dao和service的接口和实现类

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

    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();
    
    ......   
}
/**
 * 账户的业务层实现类(调用dao层的方式实现CRUD)
 * 需要使用dao对象(注入依赖)
 */
public class AccountServiceImpl implements IAccountService{

    private IAccountDao accountDao;

    // xml配置就需要set方法注入依赖
    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

	......
}

dao层的实现类:用到DBUtils

/**
 * 账户的持久层实现类
 */
public class AccountDaoImpl implements IAccountDao {

	//也是需要引入一个QueryRunner的依赖
    private QueryRunner runner;

    //也要注入set方法
    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }

    @Override
    public List<Account> findAllAccount() {
        try{
            return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

2、Spring的IOC配置

(1)在Spring官网引入xml的头

<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">
</beans>

(2)配置那些依赖对象,例如service和dao以及QueryRunner

<!-- 配置Service -->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
        <!-- 注入dao -->
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!--配置Dao对象-->
    <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
        <!-- 注入QueryRunner -->
        <property name="runner" ref="runner"></property>
    </bean>

    <!--配置QueryRunner-->
    //多个dao使用runner,则使用多例对象来实现多线程 
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <!--注入数据源(连接池)-->
        //runner在包中,不能使用set方法注入,只能使用构造函数方法注入
        <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="xmgl0609"></property>
    </bean>

3、测试类

/**
* 测试类
*/
public class AccountServiceTest {

	/**
	* 测试查询所有
	*/
	@Test
	public void testFindAllAccount() {
		//1.创建容器
		ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
		//2.得到业务层的对象
		IAccountService as = ac.getBean("accountService",IAccountService.class);
		//3.执行方法
		List<Account> list = as.findAllAccount();
		for(Account account : list) {
			System.out.println(account);
		}
	}

	......
}

4、分析问题

通过上面的测试类,我们可以看出,每个测试方法都重新获取了一次 spring 的核心容器,造成了不必要的重复代码,增加了我们开发的工作。这种情况,在开发中应该避免发生。

有些同学可能想到了,我们把容器的获取定义到类中去。例如:

/**
* 测试类
*/
public class AccountServiceTest {

	private ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
	private IAccountService as = ac.getBean("accountService",IAccountService.class);
		.......
}

这种方式虽然能解决问题,但是仍然需要我们自己写代码来获取容器。

能不能测试时直接就编写测试方法,而不需要手动编码来获取容器呢?

二、Spring中的IOC常用注解和注解方式实现单表的CRUD操作

学习基于注解的 IoC 配置,大家脑海里首先得有一个认知,即注解配置和 xml 配置要实现的功能都是一样的,都是要降低程序间的耦合。只是配置的形式不一样。

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

曾经XML的配置:(注解只是实现这些功能

<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"
       scope=""  init-method="" destroy-method="">
      <property name=""  value="" | ref=""></property>
</bean>

1、环境搭建

第一步:拷贝必备 jar 包到工程的 lib 目录。
注意:在基于注解的配置中,我们还要多拷贝一个 aop 的 jar 包。如下图:
在这里插入图片描述

第二步:使用@Component 注解配置管理的资源

/**
* 账户的业务层实现类
*/
@Component("accountService")
public class AccountServiceImpl implements IAccountService {

	private IAccountDao accountDao;
	public void setAccountDao(IAccountDao accountDao) {
		this.accountDao = accountDao;
	}
}
/**
* 账户的持久层实现类
*/
@Component("accountDao")
	public class AccountDaoImpl implements IAccountDao {
	private DBAssit dbAssit;
}

注意:当我们使用注解注入时,set 方法不用写

第三步:创建 spring的xml配置文件开启对注解的支持
注意:基于注解整合时,导入约束时需要多导入一个 context 名称空间下的约束。
由于我们使用了注解配置,此时不能在继承 JdbcDaoSupport,需要自己配置一个 JdbcTemplate

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

<!-- 告知 spring 创建容器时要扫描的包 -->
<context:component-scan base-package="com.supuEmbedded"></context:component-scan>

</beans>

2、常用注解

(1)用于创建对象的
他们的作用就和在XML配置文件中编写一个< bean>标签实现的功能是一样的

@Component:
作用:用于把当前类对象存入spring容器中方便在另一层或类中获取
属性:
value:用于指定bean的id。当我们不写时,它的默认值是当前类名,且首字母改小写。

(常用)
@Controller:一般用在表现层
@Service:一般用在业务层
@Repository:一般用在持久层

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

(2)用于注入数据的
他们的作用就和在xml配置文件中的bean标签中写一个<property>标签的作用是一样的

细节:在使用注解注入时,set方法就不是必须的了。

1.@Autowired:
作用:自动按照类型注入。只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功
如果ioc容器中没有任何bean的类型和要注入的变量类型匹配,则报错。
如果Ioc容器中有多个类型匹配时:在这里插入图片描述
出现位置:
可以是变量上,也可以是方法上

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

3.@Resource(常用)
作用:直接按照bean的id注入。它可以独立使用
属性:
name:用于指定bean的id。

以上三个注入都只能注入其他bean类型的数据,而基本类型和String类型无法使用上述注解实现
另外,集合类型的注入只能通过XML来实现。

4.@Value
作用:用于注入基本类型和String类型的数据
属性:
value:用于指定数据的值。它可以使用spring中SpEL(也就是spring的el表达式)
SpEL的写法:${表达式}从Spring中获取数据

(3)用于改变作用范围的
他们的作用就和在bean标签中使用scope属性实现的功能是一样的
@Scope
作用:用于指定bean的作用范围
属性:
value:指定范围的取值。常用取值:singleton prototype(单例多例)

(4)和生命周期相关 了解
他们的作用就和在bean标签中使用init-method和destroy-methode的作用是一样的
@PostConstruct
作用:用于指定初始化方法
@PreDestroy
作用:用于指定销毁方法

3、关于 Spring 注解和 XML 的比较

注解的优势:配置简单,维护方便我们找到类,就相当于找到了对应的配置)。
XML 的优势:修改时,不用改源码。不涉及重新编译和部署。

Spring 管理 Bean 方式的比较:
在这里插入图片描述

4、注解方式实现单表的CRUD操作

使用注解方法实现时:

(1)实现类不用写set方法,直接使用注解引入依赖
@Service(“accountService”)和 @Repository(“accountDao”)代表业务层和持久层
@Autowired表示自动查找注入依赖(只有一个时使用)

/**
 * 账户的业务层实现类
 */
@Service("accountService")
public class AccountServiceImpl implements IAccountService{

    @Autowired
    private IAccountDao accountDao;

    @Override
    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }
    ......
}
/**
 * 账户的持久层实现类
 */
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {

    @Autowired
    private QueryRunner runner;

    
    @Override
    public List<Account> findAllAccount() {
        try{
            return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
        ......
}

(2)IOC配置修改:
1、需要引入注解xml的头,在Spring官网
2、不需要再注入servcie等的依赖关系,但数据源(连接池)的依赖仍然需要注入,不能在包中写注解
3、需要提前告知spring在创建容器时要扫描的包
<context:component-scan base-package="com.itheima"></context:component-scan>

故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.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/eesy"></property>
        <property name="user" value="root"></property>
        <property name="password" value="1234"></property>
    </bean>
</beans>

(3)测试即可…

三、基于注解的纯注解方式的IOC案例

1、新增注解

(1)@Configuration

作用:指定当前类是一个配置类(此为bean.xml)

细节:当配置类作为AnnotationConfigApplicationContext()对象创建的参数时,该注解可以不写

(2)@ ConponentScan

作用:用于通过注解指定Spring在创建容器时要扫描的包

属性:
value:它和basePackages的作用一样,都是用于指定创建容器时要创建的包

则使用此注解就等同于在xml中配置了 <context:component-scan base-package=“com.itheima”></context:component-scan>

(3) Bean(作用于 包中不能写注解的对象 )
作用:用于把当前方法的返回值作为bean对象存入Spring的ioc容器中
属性:
name:用于指定bean的id,默认值是当前方法的名称

细节:当使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象
查找的方式与Autowired注解的作用是一致的

例如:
1.配置QueryRunner进IOC容器时(操作数据库对象)

<!--配置QueryRunner-->  
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
	<!--注入数据源-->
	<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>

之后就可以直接写 @Bean(name = “runner”)

@Bean(name = "runner")
@Scope(value = "prototype")
public QueryRunner createQueryRunner(@Qualifier("dataSource")DataSource dataSource) {
        //实际上DataSource参数前面有Autowired
        return new QueryRunner(dataSource);
    }

2.配置数据源进IOC容器时

<!-- 配置数据源 -->
<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="xmgl0609"></property>
</bean>

之后就可以直接写

@Bean(name = "dataSource")
    public DataSource creatDataSource1() {

        ComboPooledDataSource ds = new ComboPooledDataSource();
        try {
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(user);
            ds.setPassword(password);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        return ds;
    }

(4) AnnotationConfigApplicationContext()
通过注解获取IOC容器时,测试类必须通过此才能获取容器,从而得到Service对象

//1.获取容器
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
//2.得到业务层对象
IAccountService as = ac.getBean("accountService",IAccountService.class);

(5)Import(多个配置类,例如:jdbc,事务配置类)
一个SpringConfiguration,可能有多个小的配置类:jdbc,事务配置类

作用:导入其他的配置类,写在总的配置类中
属性:
value:用于指定其他配置类的字节码
当我们使用import的注解之后,有import注解的类就父配置类,而导入的都是子配置类
例如:

@Import({ JdbcConfig.class})

(6) PropertySource
作用:用于指定properties文件的位置

可能会将一些配置信息,存入properties 文件中,配置类从文件中获取。从而让配置类定位配置信息文件。

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

2、案例代码

(1)结构:
在这里插入图片描述
(2)代码如下:
1、配置文件

/**
 * 该类是一个配置类,作用于bean.xml作用一样
 * @author Mango
 */
@Configuration
@ComponentScan(basePackages = "com.itheima")
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {

	//使用PropertySource获取配置文件信息
    @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对象
     * @param dataSource
     * @return
     */
    @Bean(name = "runner")
    @Scope(value = "prototype")
    //采用多例对象,可能有 多个dao使用多个QueryRunner
    public QueryRunner createQueryRunner(@Qualifier("ds1")DataSource dataSource) {
        //实际上DataSource参数前面有Autowired
        return new QueryRunner(dataSource);
    }

    /**
     * 创建数据源对象
     * @return
     */
    @Bean(name = "dataSource")
    public DataSource creatDataSource() {

        ComboPooledDataSource ds = new ComboPooledDataSource();
        try {
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(user);
            ds.setPassword(password);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        return ds;
    }

    /**
     * 创建数据源对象
     * @return
     */
    @Bean(name = "ds1")
    public DataSource creatDataSource1() {

        ComboPooledDataSource ds = new ComboPooledDataSource();
        try {
            ds.setDriverClass(driver);
            ds.setJdbcUrl("jdbc:mysql://localhost:3306/eesy02");
            ds.setUser(user);
            ds.setPassword(password);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        return ds;
    }
}

2、dao和service直接从Spring容器中获取对象

**
 * 账户的持久层实现类
 */
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {

    @Autowired
    private QueryRunner runner;



    @Override
    public List<Account> findAllAccount() {
        try{
            return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
	......
}
**
 * 账户的业务层实现类
 */
@Service("accountService")
public class AccountServiceImpl implements IAccountService{

    @Autowired
    private IAccountDao accountDao;

    @Override
    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }
    ......
}

3、分析测试类中的问题
通过上面的测试类,我们可以看出,每个测试方法都重新获取了一次 spring 的核心容器,造成了不必要的重复代码,增加了我们开发的工作量。这种情况,在开发中应该避免发生。

有些同学可能想到了,我们把容器的获取定义到类中去。例如:

/**
* 测试类
*/
public class AccountServiceTest {
	//1.手动获取容器
	private ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
	//2.得到业务层对象
	private IAccountService as = ac.getBean("accountService",IAccountService.class);
	......	
}

这种方式虽然能解决问题,但是扔需要我们自己写代码来获取容器。能不能测试时直接就编写测试方法,而不需要手动编码来获取容器呢?

我们可以使用junit和spring进行整合(合体)

四、Spring和Junit的整合

1、解决思路

针对上述问题,我们需要的是程序能自动帮我们创建容器

我们知道,junit 单元测试的原理(在 web 阶段课程中讲过),但显然,junit 是无法实现的,因为它自己都无法知晓我们是否使用了 spring 框架,更不用说帮我们创建 spring 容器了。不过好在,junit 给我们暴露了一个注解,可以让我们替换掉它的运行器。

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

2、整合步骤

(1)导入Spring整合junit的jar包(与Spring配套的junit测试类的包)

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

(2)使用junit提供的注解 @Runwith 使得原有的main方法替换成Spring提供的
(3)使用 @ContextConfiguration 告知spring的运行器,spring和ioc创建时基于xml还是注解的,并且说明位置

locations:指定xml文件的位置,加上classpath关键字表示在类路径下(xml配置)
例如:locations = classpath:bean.xml

classes:指定注解类所在地位置的class文件(注解配置)

(4)使用**@Autowired** 给测试类中的变量注入数据

直接可以使用@Autowired 来获取需要的对象(例如:业务层对象)

//自动创建SpringIoc容器
@RunWith(SpringJUnit4ClassRunner.class)
//指定配置类的位置
@ContextConfiguration(classes = SpringConfiguration.class)

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);
        }
    }
    ......
}
发布了47 篇原创文章 · 获赞 18 · 访问量 4873

猜你喜欢

转载自blog.csdn.net/qq_43605085/article/details/98729795