spring 英文翻译为:春天;恰好现在也是这个季节;象征春招开始,百花齐放,时不我待的时候;正如伟大的毛主席所说:你们青年人朝气蓬勃,正在兴旺时期,好像早上八、九点的太阳,希望就在你们身上!
spring
一、概述以及即基于XML的IOC配置
1.1 spring 概述
spring 是什么?
- Spring 是分层的 Java SE/EE 应用 full-stack 轻量级开源框架,以 IoC(Inverse Of Control:
反转控制)和 AOP(Aspect Oriented Programming:面向切面编程)为内核,提供了展现层Spring MVC 和持久层 Spring JDBC 以及业务层事务管理等众多的企业级应用技术,还能整合开源世界众多著名的第三方框架和类库,逐渐成为使用最多的 Java EE 企业应用开源框架
spring 的优势
- 方便解耦,简化开发
- AOP 编程的支持
- 声明式事务的支持
- 方便程序的测试
- 方便集成各种优秀框架
- 降低 JavaEE API 的使用难度
- Java 源码是经典学习范例
spring 的体系结构
- 核心容器(Core Container) 、 AOP(Aspect Oriented Programming)和设备支持(Instrmentation) 、数据访问与集成(Data Access/Integeration) 、 Web、 消息(Messaging) 、 Test等 6 个模块, 以下是 Spring 5 的模块结构图:
1.2 程序中的耦合以及解耦
耦合:简单来说就是程序间的依赖关系
1.2.1 JDBC 代码耦合分析
- 我们先来看一段 JDBC获取数据库连接,执行sql语句的代码:
public class JdbcDemo1 {
public static void main(String[] args) throws Exception{
//1.注册驱动
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//2.获取连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/eesy","root","1234");
//3.获取操作数据库的预处理对象
PreparedStatement pstm = conn.prepareStatement("select * from account");
//4.执行SQL,得到结果集
ResultSet rs = pstm.executeQuery();
//5.遍历结果集
while(rs.next()){
System.out.println(rs.getString("name"));
}
//6.释放资源
rs.close();
pstm.close();
conn.close();
}
}
- 对于上述代码,相信大家并不陌生,通过JDBC获取数据库连接,然后执行SQL语句,通过结果集接受返回结果,然后遍历结果集。
但大家在第一步:注册驱动 的时候,并不是采用 new 的方式,而是反射加载驱动:
Class.forName("com.mysql.jdbc.Driver");
- 问题一: 那么我现在把驱动驱动写成:new com.mysql.jdbc.Driver() ,想表达什么?
结果:当我们工程把“数据库连接依赖”去掉之后,我们运行程序,程序报错:编译器异常
Compilation completed with 1 error and 0 warnings
- 结论: 采用new com.mysql.jdbc.Driver() 方式会导致,如果没有这个驱动类,那么我们的程序就无法再往下执行,也就是我们程序一开始就和这个驱动类有很强的耦合关系,这是我们开发中坚决要避免的问题
- 解决:
通过反射的方式注册驱动
:Class.forName(“com.mysql.jdbc.Driver”),这时候com.mysql.jdbc.Driver只是一个字符串,就算上面通过反射获取驱动类出错,那么我们程序也是运行期抛出的异常,编译期是正常的! - 问题2:还有一个问题就是通过反射的方式会把我们的驱动类写死,我们的数据库不一定是mysql数据库,怎么方便更改
- 解决:
通过读取配置文件的方式来获取创建对象的全限定类名
1.2.2 工厂模式解耦
- 下面我们简单的写一个模拟保存账户的业务:
我们知道业务层调用持久层、表现层调用业务层,所以我们来看看账户的业务层实现类和表现层代码:
/**
* 账户的业务层实现类
*/
public class AccountServiceImpl implements IAccountService {
//业务层调用持久层(和数据库打交道)
private IAccountDao accountDao = new AccountDaoimpl();
public void saveAccount() {
accountDao.saveAccount();
}
}
/**
* 模拟一个表现层调用业务层
*/
public class Client {
public static void main(String[] args) {
IAccountService as = new AccountServiceImpl();
as.saveAccount();
}
}
- 我们看到了,我们业务层调用持久层和表现层调用业务层都使用的是 new 关键字,这就表明存在依赖关系,那我们怎么降低耦合/依赖关系呢?
- 回答:
工厂模式解耦
,那么我们现在要清楚我们工厂是来干嘛的,它就是来创建我们的 service 和 dao 对象的 - 怎么创建: 通过上面JDBC 案例分析,我们可以知道 1、我们需要一个配置文件来配置我们的service和dao,配置的内容(key-value):唯一标识-全限定类名;2、通过配置文件来获取配置中的内容,反射创建对象
- 1、配置文件:
2、读取配置文件,反射创建对象
/**
* 创建service和dao对象
* 1、配置文件
* 2、通过读取配置文件内容反射创建对象
*/
public class BeanFactory {
//实例化对象
private static Properties props;
//定义一个人map用于存放创建的对象
private static Map<String,Object>beans;
//使用静态变量为Properties赋值
static {
try {
props = new Properties();
//获取Properties文件的流对象
InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
props.load(in);
//实例化容器
beans = new HashMap<String, Object>();
//取出配置文件中所有的key
Enumeration<Object> keys = props.keys();
//遍历枚举
while (keys.hasMoreElements()){
String key = keys.nextElement().toString();
String beanPath = props.getProperty(key);
Object value = Class.forName(beanPath).newInstance();
beans.put(key,value);
}
} catch (Exception e) {
throw new ExceptionInInitializerError("初始化Properties失败");
}
}
/**
* 根据name获取bean对象
* @param name
* @return
*/
public static Object getBean(String name){
return beans.get(name);
}
}
- 分析:对于上述配置文件代码,有几点我们需要了解和学习,我们看到了:我们把解析的配置文件内容存入到我们的 Map 中,那么在我们通过 getBean(String name) 获取对象的时候,那么name相同时,获取的创建的对象永远是一样的,因为:
Object value = Class.forName(beanPath).newInstance();
- 只执行的一次,也就是我们采用的是单例模式来获取对象,提高程序的运行效率
注意: 单例模式也存在线程安全问题,当我们通过单例模式获取类成员变量时候,例如对类成员变量:i++操作,多线程下可能会出现线程安全问题 - 通过工厂模式,我们业务层调用持久层和表现层调用业务层就调用:getBean 方法就好:
/**
* 账户的业务层实现类
*/
public class AccountServiceImpl implements IAccountService {
//业务层调用持久层(和数据库打交道)
private IAccountDao accountDao = new AccountDaoimpl();
// IAccountDao accountDao =(IAccountDao)BeanFactory.getBean("accountDao");
public void saveAccount() {
accountDao.saveAccount();
}
}
从上面代码,我们也可以理解 IOC 思想
:控制反转,我们要么使用 new关键字创建对象,要么使用工厂给我们创建对象;但是通过 new 关键字创建的对象的权力在我们手上,我们要使用什么对象,就new什么类;但是工厂模式创建对象,它把创建对象的权力交给了BeanFactory这个类,至于创建什么对象,是由getBean(“xxxx参数”)参数来控制的,所以控制权发生了反转!
1.3 IOC的概念和sping中的IOC
工厂模式解耦:
在实际开发中我们可以把三层的对象都使用配置文件配置起来,当启动服务器应用加载的时候,让一个类中的方法通过读取配置文件,把这些对象创建出来并存起来。在接下来的使用的时候,直接拿过来用就好了。那么,这个读取配置文件,创建和获取三层对象的类就是工厂控制反转-Inversion Of Control:
1、存哪去:
分析:由于我们是很多对象,肯定要找个集合来存。这时候有 Map 和 List 供选择。
到底选 Map 还是 List 就看我们有没有查找需求。有查找需求,选 Map。
所以我们的答案就是
在应用加载时,创建一个 Map,用于存放三层对象。
我们把这个 map 称之为容器
。
2、还是没解释什么是工厂?
工厂就是负责给我们从容器中获取指定对象的类。这时候我们获取对象的方式发生了改变。
原来:我们在获取对象时,都是采用 new 的方式。是主动的
现在:我们获取对象时,同时跟工厂要,有工厂为我们查找或者创建对象。是被动的
这种被动接收的方式获取对象的思想就是控制反转
,它是 spring 框架的核心之一。
1.3.1 IOC 概念和作用
- 控制反转-Inversion Of Control概念:把创建对象的权力交给框架,是框架的重要特征,并非面向对象编程的专业术语。它包括依赖注入(DI)和依赖查找(DL)
- 作用:削减计算机程序的耦合(解除代码中的依赖关系)
1.3.2 使用IOC解决程序耦合
- 说明: 以下案例分析包含很多重要知识点,我会加粗/红体标注
- 准备:这里我使用的案例是,账户的业务层和持久层的依赖关系解决。在开始 spring 的配置之前,我们要先准备一下环境。由于我们是使用 spring 解决依赖关系,并不是真正的要做增删改查操作,所以此时我们没必要写实体类。并且我们在此处使用的是 java 工程,不是 java web 工程
1、工程如下:
2、创建业务层接口和实现类
/**
* 账户的业务层实现类
*/
public class AccountServiceImpl implements IAccountService {
//业务层调用持久层(和数据库打交道)
private IAccountDao accountDao = new AccountDaoimpl();
public void saveAccount() {
accountDao.saveAccount();
}
}
/**
* 业务层接口
*/
public interface IAccountService {
/**
* 模拟保存
*/
void saveAccount();
}
3、创建持久层接口和实现类
/**
* 账户的持久层接口
*/
public interface IAccountDao {
void saveAccount();
}
/**
* 账户的持久层实现类
*/
public class AccountDaoimpl implements IAccountDao {
public void saveAccount() {
System.out.println("保存了账户");
}
}
一、基于 XML 的配置
- 1、导入依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
- 2、在类的根路径下创建一个任意名称的 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">
</beans>
- 3、让 spring 管理资源,在配置文件中配置 service 和 dao
<!-- bean 标签:用于配置让 spring 创建对象,并且存入 ioc 容器之中
id 属性:对象的唯一标识。
class 属性:指定要创建对象的全限定类名
-->
<!-- 配置 service -->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
</bean>
<!-- 配置 dao -->
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl"></bean>
- 4、测试配置是否成功
public static void main(String[] args) {
//1、获取核心容器(map)
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2、根据id获取对象
IAccountService as = (IAccountService)ac.getBean("accountService");
IAccountDao adao = ac.getBean("accountDao",IAccountDao.class);
System.out.println(as+" "+adao);
}
}
二、基于 XML 的IOC细节
- 1、ApplicationContext 接口的实现类
ClassPathXmlApplicationContext:它是从类的根路径下加载配置文件 推荐使用这种
FileSystemXmlApplicationContext:它是从磁盘路径上加载配置文件,配置文件可以在磁盘的任意位置。
AnnotationConfigApplicationContext:当我们使用注解配置容器对象时,需要使用此类来创建 spring 容器。它用来读取注解。 - 2、BeanFactory 和 ApplicationContext 的区别
BeanFactory 才是 Spring 容器中的顶层接口。
ApplicationContext 是它的子接口。
BeanFactory 和 ApplicationContext 的区别:
创建对象的时间点不一样。
ApplicationContext:只要一读取配置文件,默认情况下就会创建对象。
BeanFactory:什么使用什么时候创建对象。
三、IOC 中 bean 标签和管理对象细节
- 1、bean 标签
- 2、bean 的作用范围和生命周期
四、实例化 Bean 的三种方式
- 1、第一种方式:使用默认无参构造函数
<!--在默认情况下:
它会根据默认无参构造函数来创建类对象。如果 bean 中没有默认无参构造函数,将会创建失败。-->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"/>
- 2、第二种方式:spring 管理静态工厂-使用静态工厂的方法创建对象
/**
* 模拟一个静态工厂,创建业务层实现类
*/
public class StaticFactory {
public static IAccountService createAccountService(){
return new AccountServiceImpl();
} }
<!-- 此种方式是:
使用 StaticFactory 类中的静态方法 createAccountService 创建对象,并存入 spring 容器
id 属性:指定 bean 的 id,用于从容器中获取
class 属性:指定静态工厂的全限定类名
factory-method 属性:指定生产对象的静态方法
--> <bean id="accountService"
class="com.itheima.factory.StaticFactory"
factory-method="createAccountService"></bean>
- 3、第三种方式:spring 管理实例工厂-使用实例工厂的方法创建对象
/**
* 模拟一个实例工厂,创建业务层实现类
* 此工厂创建对象,必须现有工厂实例对象,再调用方法
*/
public class InstanceFactory {
public IAccountService getAccount(){
return new AccountServiceImpl();
}
}
<!-- 此种方式是:
先把工厂的创建交给 spring 来管理。
然后在使用工厂的 bean 来调用里面的方法
factory-bean 属性:用于指定实例工厂 bean 的 id。
factory-method 属性:用于指定实例工厂中创建对象的方法。
<bean id="instancFactory" class="com.itheima.factory.InstanceFactory"></bean>
<bean id="accountService"
factory-bean="instancFactory"
factory-method="createAccountService"></bean>
-->
1.4 依赖注入
- 1、依赖注入的概念:
依赖注入:Dependency Injection。它是 spring 框架核心 ioc 的具体实现。
我们的程序在编写时,通过控制反转,把对象的创建交给了 spring,但是代码中不可能出现没有依赖的情况。
ioc 解耦只是降低他们的依赖关系,但不会消除。例如:我们的业务层仍会调用持久层的方法。
那这种业务层和持久层的依赖关系,在使用 spring 之后,就让 spring 来维护了。
简单的说,就是坐等框架把持久层对象传入业务层,而不用我们自己去获取。 - 2、构造函数注入
顾名思义,就是使用类中的构造函数,给成员变量赋值。注意,赋值的操作不是我们自己做的,而是通过配置
的方式,让 spring 框架来为我们注入。具体代码如下:
/**
* 账户的业务层实现类
*/
public class AccountServiceImpl implements IAccountService {
//如果是经常变化的数据,并不适用于注入的方式
private String name;
private Integer age;
private Date birthday;
public AccountServiceImpl(String name,Integer age,Date birthday){
this.name = name;
this.age = age;
this.birthday = birthday;
}
public void saveAccount(){
System.out.println("service中的saveAccount方法执行了。。。"+name+","+age+","+birthday);
}
}
<!-- 使用构造函数的方式,给 service 中的属性传值
要求:
类中需要提供一个对应参数列表的构造函数。
涉及的标签:
constructor-arg
属性:
index:指定参数在构造函数参数列表的索引位置
type:指定参数在构造函数中的数据类型
name:指定参数在构造函数中的名称 用这个找给谁赋值
=======上面三个都是找给谁赋值,下面两个指的是赋什么值的==============
value:它能赋的值是基本数据类型和 String 类型
ref:它能赋的值是其他 bean 类型,也就是说,必须得是在配置文件中配置过的 bean
-->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"> <constructor-arg name="name" value="张三"></constructor-arg> <constructor-arg name="age" value="18"></constructor-arg> <constructor-arg name="birthday" ref="now"></constructor-arg>
</bean> <bean id="now" class="java.util.Date"></bean>
- set方法注入
顾名思义,就是在类中提供需要注入成员的 set 方法。具体代码如下:
/**
* 账户的业务层实现类
*/
public class AccountServiceImpl2 implements IAccountService {
//如果是经常变化的数据,并不适用于注入的方式
private String name;
private Integer age;
private Date birthday;
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public void saveAccount(){
System.out.println("service中的saveAccount方法执行了。。。"+name+","+age+","+birthday);
}
}
<!-- 通过配置文件给 bean 中的属性传值:使用 set 方法的方式
涉及的标签:
property
属性:
name:找的是类中 set 方法后面的部分
ref:给属性赋值是其他 bean 类型的
value:给属性赋值是基本数据类型和 string 类型的
实际开发中,此种方式用的较多。
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"> <property name="name" value="test"></property> <property name="age" value="21"></property> <property name="birthday" ref="now"></property>
</bean> <bean id="now" class="java.util.Date"></bean>
-->
- 注入集合属性
顾名思义,就是给类中的集合成员传值,它用的也是set方法注入的方式,只不过变量的数据类型都是集合。
我们这里介绍注入数组,List,Set,Map,Properties。具体代码如下:
/**
* 账户的业务层实现类
*/
public class AccountServiceImpl3 implements IAccountService {
private String[] myStrs;
private List<String> myList;
private Set<String> mySet;
private Map<String,String> myMap;
private Properties myProps;
public void setMyStrs(String[] myStrs) {
this.myStrs = myStrs;
}
public void setMyList(List<String> myList) {
this.myList = myList;
}
public void setMySet(Set<String> mySet) {
this.mySet = mySet;
}
public void setMyMap(Map<String, String> myMap) {
this.myMap = myMap;
}
public void setMyProps(Properties myProps) {
this.myProps = myProps;
}
public void saveAccount(){
System.out.println(Arrays.toString(myStrs));
System.out.println(myList);
System.out.println(mySet);
System.out.println(myMap);
System.out.println(myProps);
}
}
<!-- 注入集合数据
List 结构的:
array,list,set
Map 结构的
map,entry,props,prop
--> <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
<!-- 在注入集合数据时,只要结构相同,标签可以互换 -->
<!-- 给数组注入数据 --> <property name="myStrs"> <set><value>AAA</value> <value>BBB</value> <value>CCC</value>
</set>
</property>
<!-- 注入 list 集合数据 --> <property name="myList"> <array> <value>AAA</value> <value>BBB</value> <value>CCC</value>
</array>
</property>
<!-- 注入 set 集合数据 --> <property name="mySet"> <list><value>AAA</value> <value>BBB</value> <value>CCC</value>
</list>
</property>
<!-- 注入 Map 数据 --> <property name="myMap"> <props> <prop key="testA">aaa</prop> <prop key="testB">bbb</prop>
</props>
</property>
<!-- 注入 properties 数据 -->
<property name="myProps"> <map><entry key="testA" value="aaa"></entry> <entry key="testB"> <value>bbb</value>
</entry>
</map>
</property>
</bean>
二、基于注解的IOC及其案例
- 下面讲解注解配置时,采用上面的案例,然后把 spring 的 xml 配置内容改为使用注解逐步实现
下面是我们会用到的注解配置,前后对比!
* 曾经XML的配置:
* <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"
* scope="" init-method="" destroy-method="">
* <property name="" value="" | ref=""></property>
* </bean>
*
* 用于创建对象的
* 他们的作用就和在XML配置文件中编写一个<bean>标签实现的功能是一样的
* Component:
* 作用:用于把当前类对象存入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-methode的作用是一样的
* PreDestroy
* 作用:用于指定销毁方法
* PostConstruct
* 作用:用于指定初始化方法
*/
2.1 基于注解的 IOC配置
- 1、导入依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
- 2、使用 @Component 注解 配置管理的资源
它的作用就和在XML配置文件中编写一个标签实现的功能是一样的
作用:用于把当前类对象存入spring容器中
属性: value:用于指定bean的id。当我们不写时,它的默认值是当前类名,且首字母改小写
@Component ("accountService")
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao = null;
public void saveAccount(){
accountDao.saveAccount();
}
}
- 3、创建 spring 的 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.itheima"></context:component-scan>
</beans>
- 程序现在还不能运行,因为:上面AccountServiceImpl类里面的IAccountDao属性,我们还未赋值,运行得话,方法saveAccount()会报空指针异常,所以我们下面我们讲第二类注解:注入数据
Autowired:
- 作用:自动按照类型注入。只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功;如果ioc容器中没有任何bean的类型和要注入的变量类型匹配,则报错:
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao = null;
public void saveAccount(){
accountDao.saveAccount();
}
}
- 我们还发现一个细节:在使用注解注入时,set方法可以不写,那么我们会好奇,它怎么注入成功的,下面来画图分析下:
- 我们知道spring容器是Map结构,里面存放的:key(String类型)就是注解中id的内容,Value(Object类型):存放的就是被注解所标注的类及其实现的接口;Autowired注解是:按照类型注入,以:
@Autowired
private IAccountDao accountDao = null;
-
为栗,那么此注解就会跳过Map中的key,直接到value中去找匹配的IAccountDao,找到了吗?找到了,因为我们的value中包含:public class AccountDaoImpl implements IAccountDao,所以会把AccountDaoImpl注入进去,那么我们的变量就有值了!
-
现在还有一个新的问题:如果Ioc容器中有多个类型匹配时怎么办,那就是当我们还有一个持久层实现类实现IAccountDao接口,然后给这个实现类也加上注解,那么Autowired在扫描的时候,会扫描到两个对应类型的value,程序会报错,两个问题:1、为什么会报错,也就是当Ioc容器中有多个类型匹配时,是如何匹配的;2、如何解决?
-
1、这里我就说结论: 当Ioc容器中有多个类型匹配时,以:
@Autowired
private IAccountDao accountDao = null;
- 为栗,@Autowired注解会先按照类型:IAccountDao 圈定出来匹配的对象,然后它会使用变量名称:accountDao 作为bean的名称在圈定的对象中找一样的key,找到了则注入成功,否则注入失败!
2、如何解决
Qualifier注解: 作用:在按照类中注入的基础之上再按照名称注入。它在给类成员注入时不能单独使用。但是在给方法参数注入时可以(后面会讲)
属性: value:用于指定注入bean的id。
看下面:@Qualifier必须和 @Autowired一起使用,我们可以这样理解: Autowired是确定长相(对象类型),而Qualifier是确定名字(id唯一标识),因为长相一样的可能是双胞胎,再用名字区分,就可以确定要注入的唯一对象
@Service("accountService")
//@Scope("prototype")
public class AccountServiceImpl implements IAccountService {
@Autowired
@Qualifier("accountDao1")
private IAccountDao accountDao = null;
public void saveAccount(){
accountDao.saveAccount();
}
}
- 虽然上面@Qualifier必须和 @Autowired一起使用一起使用可以完成注入,但写起来太麻烦,于是spring给我们还提供了@Resource注解
@Resource
- 作用:直接按照 Bean 的 id 注入。它也只能注入其他 bean 类型。
- 属性:name:指定 bean 的 id。
@Value
- 作用:注入基本数据类型和 String 类型数据的
- 属性:value:用于指定值
@Scope
- 作用:指定 bean 的作用范围。
- 属性:value:指定范围的值。
- 取值:singleton prototype request session globalsession
和生命周期相关的:
- @PostConstruct: 用于指定初始化方法。
@PreDestroy: 用于指定销毁方法。
2.2 基于XML的IOC案例
- 新建工程
- 1、导入依赖:
<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>
- 2、实体类:
/**
* 账户的实体类
*/
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;
/*
*这里省略get、set方法
*/
}
- 3、持久层实现类和接口
public interface IAccountDao {
/**
* 查询所有
* @return
*/
List<Account> findAllAccount();
/**
* 查询一个
* @return
*/
Account findAccountById(Integer accountId);
/**
* 保存
* @param account
*/
void saveAccount(Account account);
/**
* 更新
* @param account
*/
void updateAccount(Account account);
/**
* 删除
* @param acccountId
*/
void deleteAccount(Integer acccountId);
}
/**
* 账户的持久层实现类
*/
public class AccountDaoImpl implements IAccountDao {
private QueryRunner runner;
public void setRunner(QueryRunner runner) {
this.runner = 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 Account findAccountById(Integer accountId) {
try{
return runner.query("select * from account where id = ? ",new BeanHandler<Account>(Account.class),accountId);
}catch (Exception e) {
throw new RuntimeException(e);
}
}
public void saveAccount(Account account) {
try{
runner.update("insert into account(name,money)values(?,?)",account.getName(),account.getMoney());
}catch (Exception e) {
throw new RuntimeException(e);
}
}
public void updateAccount(Account account) {
try{
runner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}catch (Exception e) {
throw new RuntimeException(e);
}
}
public void deleteAccount(Integer accountId) {
try{
runner.update("delete from account where id=?",accountId);
}catch (Exception e) {
throw new RuntimeException(e);
}
}
}
- 4、业务层接口和实现类
public interface IAccountService {
/**
* 查询所有
* @return
*/
List<Account> findAllAccount();
/**
* 查询一个
* @return
*/
Account findAccountById(Integer accountId);
/**
* 保存
* @param account
*/
void saveAccount(Account account);
/**
* 更新
* @param account
*/
void updateAccount(Account account);
/**
* 删除
* @param acccountId
*/
void deleteAccount(Integer acccountId);
}
/**
* 账户的业务层实现类
*/
public class AccountServiceImpl implements IAccountService{
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
public List<Account> findAllAccount() {
return accountDao.findAllAccount();
}
public Account findAccountById(Integer accountId) {
return accountDao.findAccountById(accountId);
}
public void saveAccount(Account account) {
accountDao.saveAccount(account);
}
public void updateAccount(Account account) {
accountDao.updateAccount(account);
}
public void deleteAccount(Integer acccountId) {
accountDao.deleteAccount(acccountId);
}
}
- 5、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.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-->
<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="root"></property>
</bean>
</beans>
2.3 基于注解的IOC案例
- 用到的注解配置:
/**
* 该类是一个配置类,它的作用和bean.xml是一样的
* spring中的新注解
* Configuration
* 作用:指定当前类是一个配置类
* 细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写。
* ComponentScan
* 作用:用于通过注解指定spring在创建容器时要扫描的包
* 属性:
* value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包。
* 我们使用此注解就等同于在xml中配置了:
* <context:component-scan base-package="com.itheima"></context:component-scan>
* Bean
* 作用:用于把当前方法的返回值作为bean对象存入spring的ioc容器中
* 属性:
* name:用于指定bean的id。当不写时,默认值是当前方法的名称
* 细节:
* 当我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象。
* 查找的方式和Autowired注解的作用是一样的
* Import
* 作用:用于导入其他的配置类
* 属性:
* value:用于指定其他配置类的字节码。
* 当我们使用Import的注解之后,有Import注解的类就父配置类,而导入的都是子配置类
* PropertySource
* 作用:用于指定properties文件的位置
* 属性:
* value:指定文件的名称和路径。
* 关键字:classpath,表示类路径下
*/
- 我们用注解来实现spring的CRUD操作,在上面基于XML的IOC案例的工程上进行更改,我们现在要做的就是通过注解配置,我们就不用写:bean.xml这个配置文件,举个栗子:就如同我们学的mybatis框架,我们也是通过注解的形式,就代替了Mapper映射XML文件的配置
- 1、在上面工程上添加和更改,工程目录如下:
我们新增了一个config包,里面有两个类,我们看看
JdbcConfig: 和spring连接数据库相关的配置类
/**
* 和spring连接数据库相关的配置类
*/
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(@Qualifier("ds2") DataSource dataSource){
return new QueryRunner(dataSource);
}
/**
* 创建数据源对象
* @return
*/
@Bean(name="ds2")
public DataSource createDataSource(){
try {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass(driver);
ds.setJdbcUrl(url);
ds.setUser(username);
ds.setPassword(password);
return ds;
}catch (Exception e){
throw new RuntimeException(e);
}
}
}
对上面部分代码进行解释:
- SpringConfiguration: 该类是一个配置类,它的作用和bean.xml是一样的
//@Configuration
@ComponentScan("com.itheima")
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
}
- jdbcConfig.properties: 连接数据库信息的配置类,这个大家应该很熟悉了:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/eesy
jdbc.username=root
jdbc.password=root
- 注解配置业务层和持久层的实现类:
- 测试:
/**
* 使用Junit单元测试:测试我们的配置
* 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及以上
*/
1、AccountServiceTest:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
@Autowired
private IAccountService as = null;
@Test
public void testFindAll() {
//3.执行方法
List<Account> accounts = as.findAllAccount();
for(Account account : accounts){
System.out.println(account);
}
}
/*
* 这里省略别的方法测试
*/
}
2、QueryRunnerTest
/**
* 测试queryrunner是否单例
*/
public class QueryRunnerTest {
@Test
public void testQueryRunner(){
//1.获取容易
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
//2.获取queryRunner对象
QueryRunner runner = ac.getBean("runner",QueryRunner.class);
QueryRunner runner1 = ac.getBean("runner",QueryRunner.class);
System.out.println(runner == runner1);
}
}
- 说明:因博文篇幅太长,不方便观看,所以对于剩下的 AOP和JdbcTemlate 相关知识,我会写一篇新博客!