Spring框架主要的优势是在简化开发
和框架整合
上,至于如何实现就是咱们要学习Spring框架的主要内容:
简化开发: Spring框架中提供了两个大的核心技术,分别是:
1.Spring的简化操作都是基于这两块内容,所以这也是Spring学习中最为重要的两个知识点。
2.事务处理属于Spring中AOP的具体应用,可以简化项目中的事务管理,也是Spring技术中的一大亮点。
框架整合: Spring在框架整合这块已经做到了极致,它可以整合市面上几乎所有主流框架,比如:
综上所述,对于Spring的学习,主要学习四块内容:
(1)IOC
(2)整合Mybatis(IOC的具体应用)
(3)AOP
(4)声明式事务(AOP的具体应用)
官网链接: https://spring.io
需要重点关注Spring Framework
、SpringBoot
和SpringCloud
:
Spring Framework是Spring生态圈中最基础的项目,是其他项目的根基。
Core Container:核心容器,这个模块是Spring最核心的模块,其他的都需要依赖该模块
(2)AOP层
(3)数据层
(4)Web层
(5)Test层
(1)什么是控制反转呢?
new
的别人[外部]
来创建对象别人[外部]
就反转控制了数据层对象的创建权(2)Spring和IOC之间的关系是什么呢?
别人[外部]
指的就是Spring的IOC容器(3)IOC容器的作用以及内部存放的是什么?
(4)当IOC容器中创建好service和dao对象后,程序能正确执行么?
像这种在容器中建立对象与对象之间的绑定关系就要用到DI:
(1)什么是依赖注入呢?
new
的别人[外部其实指的就是IOC容器]
来给注入进来(2)IOC容器中哪些bean之间要建立依赖关系呢?
介绍完Spring的IOC和DI的概念后,我们会发现这两个概念的最终目标就是:充分解耦,具体实现:
这节比较重要,重点要理解什么是IOC/DI思想
、什么是IOC容器
和什么是Bean
:
(1)什么IOC/DI思想?
(2)什么是IOC容器?
Spring创建了一个容器用来存放所创建的对象,这个容器就叫IOC容器
(3)什么是Bean?
容器中所存放的一个个对象就叫Bean或Bean对象
(1)Spring是使用容器来管理bean对象的,那么管什么?
- 主要管理项目中所使用到的类对象,比如(Service和Dao)
(2)如何将被管理的对象告知IOC容器?
- 使用配置文件
(3)被管理的对象交给IOC容器,要想从容器中获取对象,就先得思考如何获取到IOC容器?
- Spring框架提供相应的接口
(4)IOC容器得到后,如何从容器中获取bean?
- 调用Spring框架提供对应接口中的方法
(5)使用Spring导入哪些坐标?
- 用别人的东西,就需要在pom.xml添加对应的依赖
需求分析:将BookServiceImpl和BookDaoImpl交给Spring管理,并从容器中获取对应的bean对象进行方法调用。
1.创建Maven的java项目
2.pom.xml添加Spring的依赖jar包
3.创建BookService,BookServiceImpl,BookDao和BookDaoImpl四个类
4.resources下添加spring配置文件,并完成bean的配置
5.使用Spring提供的接口完成IOC容器的创建
6.从容器中获取对象进行方法调用
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
创建BookService
,BookServiceImpl
,BookDao
和BookDaoImpl
四个类
public interface BookDao {
public void save();
}
public class BookDaoImpl implements BookDao {
@Override
public void save() {
System.out.println("book dao save ...");
}
}
public interface BookService {
public void save();
}
public class BookServiceImpl implements BookService {
private BookDao bookDao=new BookDaoImpl();
@Override
public void save() {
System.out.println("book service save ...");
bookDao.save();
}
}
resources下添加spring配置文件applicationContext.xml,并完成bean的配置
创建spring配置文件,配置对应类作为Spring管理的bean
<?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">
<!--1.导入Spring的坐标Spring-context,对应的版本号是5.2.10.RELEASE-->
<!--2.配置bean-->
<!--bean标签表示配置bean-->
<!--id属性表示给bean起名字-->
<!--class属性表示给bean定义类型-->
<bean id="bookDao" class="com.itcast.dao.impl.BookDaoImpl"></bean>
<bean id="bookService" class="com.itcast.service.impl.BookServiceImpl"></bean>
</beans>
注意事项:bean定义时id属性在同一个上下文中(配置文件)不能重复
使用Spring提供的接口完成IOC容器的创建,创建App类,编写main方法
public class App {
public static void main(String[] args) {
//获取IOC容器
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
}
}
初始化IOC容器( Spring核心容器/Spring容器),通过容器获取bean
public class App2 {
public static void main(String[] args) {
// 3.获取IOC容器
//加载文件上下文对象,也就是容器对象
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
//4.获取bean
//获取资源
BookDao bookDao = (BookDao) ctx.getBean("bookDao");
bookDao.save();
BookService bookService=(BookService) ctx.getBean("bookService");
bookService.save();
}
}
Spring的IOC入门案例已经完成,但是在BookServiceImpl
的类中依然存在BookDaoImpl
对象的new操作,它们之间的耦合度还是比较高,这块该如何解决,就需要用到下面的DI:依赖注入
。
(1) 要想实现依赖注入,必须要基于IOC管理Bean
- DI的入门案例要依赖于前面IOC的入门案例
(2) Service中使用new形式创建的Dao对象是否保留?
- 需要删除掉,最终要使用IOC容器中的bean对象
(3) Service中需要的Dao对象如何进入到Service中?
- 在Service中提供方法,让Spring的IOC容器可以通过该方法传入bean对象
(4) Service与Dao间的关系如何描述?
- 使用配置文件
需求:基于IOC入门案例,在BookServiceImpl类中删除new对象的方式,使用Spring的DI完成Dao层的注入
1.删除业务层中使用new的方式创建的dao对象
2.在业务层提供BookDao的setter方法
3.在配置文件中添加依赖注入的配置
4.运行程序调用方法
在BookServiceImpl类中,删除业务层中使用new的方式创建的dao对象
删除前
public class BookServiceImpl implements BookService {
private BookDao bookDao=new BookDaoImpl();
@Override
public void save() {
System.out.println("book service save ...");
bookDao.save();
}
}
删除后
public class BookServiceImpl implements BookService {
//5.删除业务层中使用new的方式创建的Dao对象
private BookDao bookDao;
@Override
public void save() {
System.out.println("book service save ...");
bookDao.save();
}
}
在BookServiceImpl类中,为BookDao提供setter方法
public class BookServiceImpl implements BookService {
//5.删除业务层中使用new的方式创建的Dao对象
private BookDao bookDao;
@Override
public void save() {
System.out.println("book service save ...");
bookDao.save();
}
//6.提供对应的set方法
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
}
在配置文件中添加依赖注入的配置
<bean id="bookService" class="com.itcast.service.impl.BookServiceImpl">
<!--7.配置server与dao的关系-->
<!--property标签表示配置当前bean的属性
name属性表示配置哪一个具体的属性
ref表示参照哪一个bean-->
<property name="bookDao" ref="bookDao"></property>
</bean>
完整版:
<?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">
<!--1.导入Spring的坐标Spring-context,对应的版本号是5.2.10.RELEASE-->
<!--2.配置bean-->
<!--bean标签表示配置bean-->
<!--id属性表示给bean起名字-->
<!--class属性表示给bean定义类型-->
<bean id="bookDao" class="com.itcast.dao.impl.BookDaoImpl"></bean>
<bean id="bookService" class="com.itcast.service.impl.BookServiceImpl">
<!--7.配置server与dao的关系-->
<!--property标签表示配置当前bean的属性
name属性表示配置哪一个具体的属性
ref表示参照哪一个bean-->
<property name="bookDao" ref="bookDao"></property>
</bean>
</beans>
注意:配置中的两个bookDao的含义是不一样的
bookDao
的作用是让Spring的IOC容器在获取到名称后,将首字母大写,前面加set找对应的setBookDao()
方法进行对象注入bookDao
的作用是让Spring能在IOC容器中找到id为bookDao
的Bean对象给bookService
进行注入搭建的内容和前面的一样的,内容如下:
对于bean的基础配置,在前面的案例中已经使用过:
<bean id="" class=""/>
其中,bean标签的功能、使用方式以及id和class属性的作用,我们通过一张图来描述下:
重点是:bean标签的id和class属性的使用。
打开spring的配置文件applicationContext.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">
<bean id="bookService" name="service service4 bookEbi" class="com.itcast.service.impl.BookServiceImpl">
<property name="bookDao" ref="bookDao"/>
bean>
<bean id="bookDao" name="dao" class="com.itcast.dao.impl.BookDaoImpl"/>
beans>
说明:Ebi全称Enterprise Business Interface,翻译为企业业务接口
public class AppForName {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//此处根据bean标签的id属性和name属性的任意一个值来获取bean对象
BookService bookService = (BookService) ctx.getBean("service4");
bookService.save();
}
}
测试结果为:
注意事项:
特别注意:
获取bean无论是通过id还是name获取,如果无法获取到,将抛出异常NoSuchBeanDefinitionException
同一个bean获取两次,将对象打印到控制台,看打印出的地址值是否一致。
AppForScope
的类,在其main方法中来验证public class AppForScope {
public static void main(String[] args) {
ApplicationContext ctz = new ClassPathXmlApplicationContext("applicationContext.xml");
BookService bookService1 = (BookService) ctz.getBean("bookService");
BookService bookService2 = (BookService) ctz.getBean("bookService");
System.out.println(bookService1);
System.out.println(bookService2);
}
}
在Spring配置文件中,配置scope属性来实现bean的非单例创建
在Spring的配置文件中,修改
的scope属性
<bean id="bookService" name="service service2 bookEbi" class="com.itcast.service.impl.BookServiceImpl" scope=" ">
<property name="bookDao" ref="bookDao">property>
bean>
将scope设置为singleton
<bean id="bookService" name="service service2 bookEbi" class="com.itcast.service.impl.BookServiceImpl" scope="singleton">
<property name="bookDao" ref="bookDao">property>
bean>
将scope设置为prototype
<bean id="bookService" name="service service2 bookEbi" class="com.itcast.service.impl.BookServiceImpl" scope="prototype">
<property name="bookDao" ref="bookDao">property>
bean>
运行AppForScope,打印看结果
结论,使用bean的scope
属性可以控制bean的创建是否为单例:
singleton
默认为单例prototype
为非单例为什么bean默认为单例?
bean在容器中是单例的,会不会产生线程安全问题?
哪些bean对象适合交给容器进行管理?
哪些bean对象不适合交给容器进行管理?
pom.xml
<?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.itcast</groupId>
<artifactId>spring_03_bean_instance</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
</dependencies>
</project>
BookDao.java
public interface BookDao {
public void save();
}
BookDaoImpl.java
public class BookDaoImpl implements BookDao {
public void save() {
System.out.println("book dao save ...");
}
}
applicationContext.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">
<bean id="bookDao" class="com.itcast.dao.impl.BookDaoImpl"></bean>
</beans>
在上述的环境下,我们来研究下Spring中的第一种bean的创建方式构造方法实例化
:
准备一个BookDao和BookDaoImpl类
public interface BookDao {
public void save();
}
public class BookDaoImpl implements BookDao {
public void save() {
System.out.println("book dao save ...");
}
}
<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">
<bean id="bookDao" class="com.itcast.dao.impl.BookDaoImpl"/>
beans>
public class AppForInstanceBook {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
BookDao bookDao = (BookDao) ctx.getBean("bookDao");
bookDao.save();
}
}
在BookDaoImpl类中添加一个无参构造函数,并打印一句话,方便观察结果。
public class BookDaoImpl implements BookDao {
public BookDaoImpl() {
System.out.println("book dao constructor is running ....");
}
public void save() {
System.out.println("book dao save ...");
}
}
运行程序,如果控制台有打印构造函数中的输出,说明Spring容器在创建对象的时候也走的是构造函数
public class BookDaoImpl implements BookDao {
private BookDaoImpl() {
System.out.println("book dao constructor is running ....");
}
public void save() {
System.out.println("book dao save ...");
}
}
运行程序,能执行成功,说明内部走的依然是构造函数,能访问到类中的私有构造方法,显而易见Spring底层用的是反射
public class BookDaoImpl implements BookDao {
private BookDaoImpl(int i) {
System.out.println("book dao constructor is running ....");
}
public void save() {
System.out.println("book dao save ...");
}
}
运行程序,
程序会报错,说明Spring底层使用的是类的无参构造方法。
无参构造方法如果不存在,将抛出异常BeanCreationException
接下来,我们主要研究下Spring的报错信息来学一学如阅读。
()
引起
,即出现错误的原因没有这样的方法异常
():哪个类的哪个方法没有被找到导致的异常,
()指定是类的构造方法,即该类的无参构造方法如果最后一行错误获取不到错误信息,接下来查看第二层:
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.itheima.dao.impl.BookDaoImpl]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.itheima.dao.impl.BookDaoImpl.
()
引发
bean实例化异常
看到这其实错误已经比较明显,给大家个练习,把倒数第三层的错误分析下吧:
Exception in thread “main” org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘bookDao’ defined in class path resource [applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.itheima.dao.impl.BookDaoImpl]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.itheima.dao.impl.BookDaoImpl.
()。
至此,关于Spring的构造方法实例化就已经学习完了,因为每一个类默认都会提供一个无参构造函数,所以其实真正在使用这种方式的时候,我们什么也不需要做。这也是我们以后比较常用的一种方式。
public interface OrderDao {
public void save();
}
public class OrderDaoImpl implements OrderDao {
public void save() {
System.out.println("order dao save ...");
}
}
静态方法
//静态工厂创建对象
public class OrderDaoFactory {
public static OrderDao getOrderDao(){
return new OrderDaoImpl();
}
}
public class AppForInstanceOrder {
public static void main(String[] args) {
//通过静态工厂创建对象
OrderDao orderDao= OrderDaoFactory.getOrderDao();
orderDao.save();
// ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//
// OrderDao orderDao = (OrderDao) ctx.getBean("orderDao");
//
// orderDao.save();
}
}
(1)在spring的配置文件applicationContext.xml文件中添加以下配置:
<!--方式二:使用静态工厂实例化bean-->
<bean id="orderDao" class="com.itcast.factory.OrderDaoFactory" factory-method="getOrderDao"></bean>
class:工厂类的类全名
factory-mehod:具体工厂类中创建对象的方法名
(2)在AppForInstanceOrder运行类,使用从IOC容器中获取bean的方法进行运行测试
public class AppForInstanceOrder {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
OrderDao orderDao = (OrderDao) ctx.getBean("orderDao");
orderDao.save();
}
}
//静态工厂创建对象
public class OrderDaoFactory {
public static OrderDao getOrderDao(){
System.out.println("factory setup....");//模拟必要的业务操作
return new OrderDaoImpl();
}
}
之前new对象的方式就无法添加其他的业务内容,重新运行,查看结果:
(1)准备一个UserDao和UserDaoImpl类
public interface UserDao {
public void save();
}
public class UserDaoImpl implements UserDao {
public void save() {
System.out.println("user dao save ...");
}
}
(2)创建一个工厂类OrderDaoFactory并提供一个普通方法,注意此处和静态工厂的工厂类不一样的地方是方法不是静态方法
public class UserDaoFactory {
public UserDao getUserDao(){
return new UserDaoImpl();
}
}
(3)编写AppForInstanceUser运行类,在类中通过工厂获取对象
public class AppForInstanceUser {
public static void main(String[] args) {
//创建实例工厂对象
UserDaoFactory userDaoFactory = new UserDaoFactory();
//通过实例工厂对象创建对象
UserDao userDao = userDaoFactory.getUserDao();
userDao.save();
}
在applicationContext.xml文件中添加:
<!--方式三:使用实例工厂实例化bean-->
<bean id="userFactory" class="com.itcast.factory.UserDaoFactory"></bean>
<bean id="userDao" factory-method="getUserDao" factory-bean="userFactory"></bean>
<!--- factory-bean:工厂的实例对象
factory-method:工厂对象中的具体创建对象的方法名-->
实例化工厂运行的顺序是:
创建实例化工厂对象,对应的是第一行配置
调用对象中的方法来创建bean,对应的是第二行配置
factory-mehod:具体工厂类中创建对象的方法名
(2)在AppForInstanceUser运行类,使用从IOC容器中获取bean的方法进行运行测试
public class AppForInstanceUser {
public static void main(String[] args) {
ApplicationContext ctx = new
ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao) ctx.getBean("userDao");
userDao.save();
}
}
(1)创建一个UserDaoFactoryBean类,实现FactoryBean的接口,重写接口的方法
public class UserDaoFactoryBean implements FactoryBean<UserDao> {
/*
* 代替原始实例工厂中创建对象的方法
* */
@Override
public UserDao getObject() throws Exception {
return new UserDaoImpl();
}
/*
* 返回所创建类的Class对象
* */
@Override
public Class<?> getObjectType() {
return UserDao.class;
}
}
(2)在applicationContext.xml文件中添加以下配置
<!--方式四:使用FactoryBean实例化bean-->
<bean id="userDao" class="com.itcast.factory.UserDaoFactoryBean"></bean>
(3)AppForInstanceUser运行类不用做任何修改,直接运行
public class AppForInstanceUser {
public static void main(String[] args) {
// //创建实例工厂对象
// UserDaoFactory userDaoFactory = new UserDaoFactory();
// //通过实例工厂创建对象
// UserDao userDao = userDaoFactory.getUserDao();
// userDao.save();
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao) ctx.getBean("userDao");
userDao.save();
}
}
public class AppForInstanceUser {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//检测是否为单例模式
UserDao userDao1 = (UserDao) ctx.getBean("userDao");
UserDao userDao2 = (UserDao) ctx.getBean("userDao");
System.out.println(userDao1);
System.out.println(userDao2);
}
}
(5)怎样才能为非单例模式–重写FactoryBean接口的isSingleton方法
public class UserDaoFactoryBean implements FactoryBean<UserDao> {
/*
* 代替原始实例工厂中创建对象的方法
* */
@Override
public UserDao getObject() throws Exception {
return new UserDaoImpl();
}
/*
* 返回所创建类的Class对象
* */
@Override
public Class<?> getObjectType() {
return UserDao.class;
}
//是否为单例
@Override
public boolean isSingleton() {
return false;
}
}
<?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.itcast</groupId>
<artifactId>spring_04_bean_lifecycle</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
</dependencies>
</project>
(2)项目中创建BookDao、BookDaoImpl、BookService、BookServiceImpl类
public interface BookDao {
public void save();
}
public class BookDaoImpl implements BookDao {
@Override
public void save() {
System.out.println("book dao save ...");
}
}
public interface BookService {
public void save();
}
public class BookServiceImpl implements BookService {
private BookDao bookDao;
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
@Override
public void save() {
System.out.println("book service save ...");
bookDao.save();
}
}
(3)修改配置文件appllicationContext.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">
<bean id="bookDao" class="com.itcast.dao.Impl.BookDaoImpl"></bean>
<bean id="bookService" class="com.itcast.service.Impl.BookServiceImpl">
<property name="bookDao" ref="bookDao"></property>
</bean>
</beans>
(4)创建AppForLifeCycle类,加载Spring的IOC容器,并从中获取对应的bean对象
public class AppForLifeCycle {
public static void main( String[] args ) {
ApplicationContext ctz=new ClassPathXmlApplicationContext("applicationContext.xml");
BookDao bookDao = (BookDao) ctz.getBean("bookDao");
bookDao.save();
}
}
在BooDaoImpl类中分别添加两个方法,方法名任意
public class BookDaoImpl implements BookDao {
public void save() {
System.out.println("book dao save ...");
}
//表示bean初始化对应的操作
public void init(){
System.out.println("init...");
}
//表示bean销毁前对应的操作
public void destory(){
System.out.println("destory...");
}
}
在配置文件添加配置,如下:
<bean id="bookDao" class="com.itcast.dao.impl.BookDaoImpl" init-method="init" destroy-method="destory"/>
从结果中可以看出,init方法执行了,但是destroy方法却未执行,这是为什么呢?
ApplicationContext中没有close方法
需要将ApplicationContext更换成ClassPathXmlApplicationContext
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
调用ctx的close()方法
ctx.close();
在容器未关闭之前,提前设置好回调函数,让JVM在退出之前回调此函数来关闭容器
调用ctx的registerShutdownHook()方法
ctx.registerShutdownHook();
注意:registerShutdownHook在ApplicationContext中也没有
相同点:这两种都能用来关闭容器
不同点:close()是在调用的时候关闭,registerShutdownHook()是在JVM退出前调用关闭。
分析上面的实现过程,会发现添加初始化和销毁方法,即需要编码也需要配置,实现起来步骤比较多也比较乱。
Spring提供了两个接口来完成生命周期的控制,好处是可以不用再进行配置init-method
和destroy-method
接下来在BookServiceImpl完成这两个接口的使用:
修改BookServiceImpl类,添加两个接口InitializingBean
, DisposableBean
并实现接口中的两个方法afterPropertiesSet
和destroy
public class BookServiceImpl implements BookService, InitializingBean, DisposableBean {
private BookDao bookDao;
public void setBookDao(BookDao bookDao) {
System.out.println("set ...");
this.bookDao = bookDao;
}
@Override
public void save() {
System.out.println("book service save ...");
bookDao.save();
}
@Override
public void destroy() throws Exception {
System.out.println("service destroy ...");
}
//属性设置之后
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("service init ...");
}
}
(1)关于Spring中对bean生命周期控制提供了两种方式:
init-method
和destroy-method
属性InitializingBean
与DisposableBean
接口。(2)对于bean的生命周期控制在bean的整个生命周期中所处的位置如下:
(3)关闭容器的两种方式:
依赖注入方式
public class BookServiceImpl implements BookService{
private BookDao bookDao;
public void setBookDao(BookDao bookDao) {
System.out.println("set ...");
this.bookDao = bookDao;
}
@Override
public void save() {
System.out.println("book service save ...");
bookDao.save();
}
}
<?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">
<bean id="bookDao" class="com.itcast.dao.Impl.BookDaoImpl" init-method="init" destroy-method="destroy"></bean>
<bean id="bookService" class="com.itcast.service.Impl.BookServiceImpl">
<property name="bookDao" ref="bookDao"></property>
</bean>
</beans>
(2)pom.xml添加依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
</dependencies>
(3)在resources目录下添加spring的配置文件applicationContext.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">
<bean name="bookDao" class="com.itcast.dao.impl.BookDaoImpl"></bean>
<bean name="bookService" class="com.itcast.service.impl.BookServiceImpl">
<property name="bookDao" ref="bookDao"></property>
</bean>
</beans>
(4)新建BookDao、BookDaoImpl、UserDao、UserDaoImpl、UserService、UserServiceImpl类及方法
public interface BookDao {
public void save();
}
public class BookDaoImpl implements BookDao {
public void save() {
System.out.println("book dao save ...");
}
}
public interface UserDao {
public void save();
}
public class UserDaoImpl implements UserDao {
public void save() {
System.out.println("user dao save ...");
}
}
public interface BookService {
public void save();
}
public class BookServiceImpl implements BookService{
private BookDao bookDao;
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
public void save() {
System.out.println("book service save ...");
bookDao.save();
}
}
(5)编写AppForDISet运行类,加载spring的IOC容器,并从中获取对应的bean对象
public class AppForDISet {
public static void main(String[] args) {
ApplicationContext ctz = new ClassPathXmlApplicationContext("applicationContext.xml");
BookService bookService = (BookService) ctz.getBean("bookService");
bookService.save();
}
}
需求:在bookServiceImpl对象中注入userDao
1.在BookServiceImpl中声明userDao属性
2.为userDao属性提供setter方法
3.在配置文件中使用property标签注入
public class BookServiceImpl implements BookService {
private BookDao bookDao;
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
@Override
public void save() {
System.out.println("book service save ...");
bookDao.save();
userDao.save();
}
}
public class BookDaoImpl implements BookDao {
@Override
public void save() {
System.out.println("book dao save ... " + databaseName + " " + connectionNum);
}
}
<?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">
<bean name="bookDao" class="com.itcast.dao.impl.BookDaoImpl"></bean>
<bean name="userDao" class="com.itcast.dao.impl.UserDaoImpl"></bean>
<bean name="bookService" class="com.itcast.service.impl.BookServiceImpl">
<property name="bookDao" ref="bookDao"></property>
<property name="userDao" ref="userDao"></property>
</bean>
</beans>
需求:给BookDaoImpl注入一些简单数据类型的数据步骤为:
1.在BookDaoImpl类中声明对应的简单数据类型的属性
2.为这些属性提供对应的setter方法
3.在applicationContext.xml中配置
思考:
引用类型使用的是
,简单数据类型还是使用ref么?
ref是指向Spring的IOC容器中的另一个bean对象的,对于简单数据类型,没有对应的bean对象,该如何配置?
在BookDaoImpl类中声明对应的简单数据类型的属性,并提供对应的setter方法
public class BookDaoImpl implements BookDao {
private int connectionNum;
private String databaseName;
public void setConnectionNum(int connectionNum) {
this.connectionNum = connectionNum;
}
public void setDatabaseName(String databaseName) {
this.databaseName = databaseName;
}
@Override
public void save() {
System.out.println("book dao save ... " + databaseName + " " + connectionNum);
}
}
在applicationContext.xml配置文件中使用property标签注入
<?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">
<bean name="bookDao" class="com.itcast.dao.impl.BookDaoImpl">
<!--注入属性-->
<property name="databaseName" value="mysql"></property>
<property name="connectionNum" value="10"></property>
</bean>
<bean name="userDao" class="com.itcast.dao.impl.UserDaoImpl"></bean>
<bean name="bookService" class="com.itcast.service.impl.BookServiceImpl">
<property name="bookDao" ref="bookDao"></property>
<property name="userDao" ref="userDao"></property>
</bean>
</beans>
说明:
value:后面跟的是简单数据类型,对于参数类型,Spring在注入的时候会自动转换,但是不能写成
<property name="connectionNum" value="abc"/>
这样的话,spring在将abc
转换成int类型的时候就会报错。
运行AppForDISet类,查看结果,说明userDao已经成功注入。
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
</dependencies>
(3)新建BookDao、BookDaoImpl、UserDao、UserDaoImpl、UserService、UserServiceImpl类及方法
public interface BookDao {
public void save();
}
public class BookDaoImpl implements BookDao {
private String databaseName;
private int connectionNum;
@Override
public void save() {
System.out.println("book dao save ... ");
}
}
public interface UserDao {
public void say();
}
public class UserDaoImpl implements UserDao {
@Override
public void say() {
System.out.println("user dao save ...");
}
}
public interface BookService {
public void say();
}
public class BookServiceImpl implements BookService {
private BookDao bookDao;
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
@Override
public void say() {
System.out.println("book service say ...");
bookDao.save();
}
}
(4)在resources目录下添加spring的配置文件applicationContext.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">
<bean name="bookDao" class="com.itcast.dao.impl.BookDaoImpl"></bean>
<bean name="bookService" class="com.itcast.service.impl.BookServiceImpl">
<property name="bookDao" ref="bookDao"></property>
</bean>
</beans>
(5)编写AppForDIConstructor运行类,加载Spring的IOC容器,并从中获取对应的bean对象
public class AppForDIConstructor {
public static void main( String[] args ) {
ApplicationContext ctz=new ClassPathXmlApplicationContext("applicationContext.xml");
BookService bookService=(BookService) ctz.getBean("bookService");
bookService.say();
}
}
在BookServiceImpl类中将bookDao的setter方法删除掉,并添加带有bookDao参数的构造方法
public class BookServiceImpl implements BookService {
private BookDao bookDao;
public BookServiceImpl(BookDao bookDao) {
this.bookDao = bookDao;
}
@Override
public void say() {
System.out.println("book service say ...");
bookDao.save();
}
}
在applicationContext.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">
<bean name="bookDao" class="com.itcast.dao.impl.BookDaoImpl"></bean>
<bean name="bookService" class="com.itcast.service.impl.BookServiceImpl">
<constructor-arg name="bookDao" ref="bookDao"></constructor-arg>
</bean>
</beans>
说明:
标签中
运行AppForDIConstructor类,查看结果,说明bookDao已经成功注入。
需求:在BookServiceImpl使用构造函数注入多个引用数据类型,比如userDao
1.声明userDao属性
2.生成一个带有bookDao和userDao参数的构造函数
3.在applicationContext.xml中配置注入
在BookServiceImpl声明userDao并提供多个参数的构造函数
public class BookServiceImpl implements BookService {
private BookDao bookDao;
private UserDao userDao;
public BookServiceImpl(BookDao bookDao, UserDao userDao) {
this.bookDao = bookDao;
this.userDao = userDao;
}
@Override
public void say() {
System.out.println("book service say ...");
bookDao.save();
userDao.say();
}
}
<?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">
<bean name="bookDao" class="com.itcast.dao.impl.BookDaoImpl"></bean>
<bean name="userDao" class="com.itcast.dao.impl.UserDaoImpl"></bean>
<bean name="bookService" class="com.itcast.service.impl.BookServiceImpl">
<constructor-arg name="bookDao" ref="bookDao"></constructor-arg>
<constructor-arg name="userDao" ref="userDao"></constructor-arg>
</bean>
</beans>
说明:这两个
的配置顺序可以任意
运行AppForDIConstructor类,查看结果,说明userDao已经成功注入。
需求:在BookDaoImpl中,使用构造函数注入databaseName和connectionNum两个参数。
参考引用数据类型的注入,我们可以推出具体的步骤为:
1.提供一个包含这两个参数的构造方法
2.在applicationContext.xml中进行注入配置
修改BookDaoImpl类,添加构造方法
public class BookDaoImpl implements BookDao {
private String databaseName;
private int connectionNum;
public BookDaoImpl(String databaseName, int connectionNum) {
this.databaseName = databaseName;
this.connectionNum = connectionNum;
}
@Override
public void save() {
System.out.println("book dao save ... " + databaseName + " " + connectionNum);
}
}
在applicationContext.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">
<bean name="bookDao" class="com.itcast.dao.impl.BookDaoImpl">
<constructor-arg name="databaseName" value="mysql"></constructor-arg>
<constructor-arg name="connectionNum" value="10"></constructor-arg>
</bean>
<bean name="userDao" class="com.itcast.dao.impl.UserDaoImpl"></bean>
<bean name="bookService" class="com.itcast.service.impl.BookServiceImpl">
<constructor-arg name="bookDao" ref="bookDao"></constructor-arg>
<constructor-arg name="userDao" ref="userDao"></constructor-arg>
</bean>
</beans>
<bean name="bookDao" class="com.itcast.dao.impl.BookDaoImpl">
<constructor-arg name="databaseName" value="mysql"></constructor-arg>
<constructor-arg name="connectionNum" value="10"></constructor-arg>
</bean>
<bean name="userDao" class="com.itcast.dao.impl.UserDaoImpl"></bean>
<bean name="bookService" class="com.itcast.service.impl.BookServiceImpl">
<constructor-arg name="bookDao" ref="bookDao"></constructor-arg>
<constructor-arg name="userDao" ref="userDao"></constructor-arg>
</bean>
方式一:删除name属性,添加type属性,按照类型注入
<bean name="bookDao" class="com.itcast.dao.impl.BookDaoImpl">
<constructor-arg type="java.lang.String" value="mysql">constructor-arg>
<constructor-arg type="int" value="10">constructor-arg>
bean>
<bean name="userDao" class="com.itcast.dao.impl.UserDaoImpl">bean>
<bean name="bookService" class="com.itcast.service.impl.BookServiceImpl">
<constructor-arg name="bookDao" ref="bookDao">constructor-arg>
<constructor-arg name="userDao" ref="userDao">constructor-arg>
bean>
方式二:删除type属性,添加index属性,按照索引下标注入,下标从0开始
<bean name="bookDao" class="com.itcast.dao.impl.BookDaoImpl">
<constructor-arg index="0" value="mysql">constructor-arg>
<constructor-arg index="1" value="666">constructor-arg>
bean>
<bean name="userDao" class="com.itcast.dao.impl.UserDaoImpl">bean>
<bean name="bookService" class="com.itcast.service.impl.BookServiceImpl">
<constructor-arg name="bookDao" ref="bookDao">constructor-arg>
<constructor-arg name="userDao" ref="userDao">constructor-arg>
bean>
setter注入
简单数据类型
<bean ...>
<property name="" value=""/>
bean>
引用数据类型
<bean ...>
<property name="" ref=""/>
bean>
构造器注入
简单数据类型
<bean ...>
<constructor-arg name="" index="" type="" value=""/>
bean>
引用数据类型
<bean ...>
<constructor-arg name="" index="" type="" ref=""/>
bean>
依赖注入的方式选择上
自动装配
(2)pom.xml添加依赖资源
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
</dependencies>
(3)创建BookDao、BookDaoImpl、BookService、BookServiceImpl类及方法
public interface BookDao {
public void save();
}
public class BookDaoImpl implements BookDao {
@Override
public void save() {
System.out.println("book dao save ...");
}
}
public interface BookService {
public void save();
}
public class BookServiceImpl implements BookService {
private BookDao bookDao;
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
@Override
public void save() {
System.out.println("book service save ...");
bookDao.save();
}
}
(4)在resources目录下添加spring的配置文件applicationContext.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">
<bean name="bookDao" class="com.itcast.dao.impl.BookDaoImpl"></bean>
<bean name="bookService" class="com.itcast.service.impl.BookServiceImpl">
<property name="bookDao" ref="bookDao"></property>
</bean>
</beans>
(5)新建AppForDIAutoware运行类,加载spring的IOC容器,并从中获取对应的bean对象
public class AppForDIAutoware {
public static void main( String[] args ) {
ApplicationContext ctz=new ClassPathXmlApplicationContext("applicationContext.xml");
BookService bookService = (BookService) ctz.getBean("bookService");
bookService.save();
}
}
自动装配只需要修改applicationContext.xml配置文件即可:
(1)将
标签删除
(2)在
标签中添加autowire属性
首先来实现按照类型注入的配置
<?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">
<bean name="bookDao" class="com.itcast.dao.impl.BookDaoImpl"></bean>
<!--autowire属性:开启自动装配,通常使用按类型装配-->
<bean name="bookService" class="com.itcast.service.impl.BookServiceImpl" autowire="byType"></bean>
</beans>
注意事项:
NoUniqueBeanDefinitionException
一个类型在IOC中有多个对象,还想要注入成功,这个时候就需要按照名称注入,配置方式为:
<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">
<bean class="com.itheima.dao.impl.BookDaoImpl"/>
<bean id="bookService" class="com.itcast.service.impl.BookServiceImpl" autowire="byName"/>
beans>
注意事项:
public class BookServiceImpl implements BookService {
private BookDao bookDao;
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
@Override
public void save() {
System.out.println("book service save ...");
bookDao.save();
}
}
1. 自动装配用于引用类型依赖注入,不能对简单类型进行操作
2. 使用按类型装配时(byType)必须保障容器中相同类型的bean唯一,推荐使用
3. 使用按名称装配时(byName)必须保障容器中具有指定名称的bean,因变量名与配置耦合,不推荐使用
4. 自动装配优先级低于setter注入与构造器注入,同时出现时自动装配配置失效
常见的集合类型:
(2)pom.xml添加依赖资源
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
</dependencies>
(3)创建BookDao、BookDaoImpl、BookService、BookServiceImpl类及方法
public interface BookDao {
public void say();
}
public class BookDaoImpl implements BookDao {
@Override
public void say() {
System.out.println("book dao say ...");
}
}
public interface BookService {
public void say();
}
public class BookServiceImpl implements BookService {
private BookDao bookDao;
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
@Override
public void say() {
System.out.println("book service say ...");
bookDao.say();
}
}
(4)在resources目录下添加spring的配置文件applicationContext.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">
<bean name="bookDao" class="com.itcast.dao.impl.BookDaoImpl"></bean>
</beans>
(5)新建AppForDICollection运行类,加载spring的IOC容器,并从中获取对应的bean对象
public class AppForDICollection {
public static void main( String[] args ) {
ApplicationContext ctz =new ClassPathXmlApplicationContext("applicationContext.xml");
BookDao bookDao = (BookDao) ctz.getBean("bookDao");
bookDao.say();
}
}
public class BookDaoImpl implements BookDao {
private int[] array;
private List<String> list;
private Set<String> set;
private Map<String,String> map;
private Properties properties;
public void setArray(int[] array) {
this.array = array;
}
public void setList(List<String> list) {
this.list = list;
}
public void setSet(Set<String> set) {
this.set = set;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
@Override
public void say() {
System.out.println("book dao say ...");
System.out.println("遍历数组:" + Arrays.toString(array));
System.out.println("遍历List" + list);
System.out.println("遍历Set" + set);
System.out.println("遍历Map" + map);
System.out.println("遍历Properties" + properties);
}
}
<?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">
<bean name="bookDao" class="com.itcast.dao.impl.BookDaoImpl">
<property name="array">
<array>
<value>100</value>
<value>300</value>
<value>800</value>
</array>
</property>
<property name="list">
<list>
<value>mysql</value>
<value>sql-server</value>
<value>navicat</value>
</list>
</property>
<property name="set">
<set>
<value>mysql</value>
<value>mysql</value>
<value>sql-server</value>
<value>sql-server</value>
<value>sql-server</value>
<value>navicat</value>
</set>
</property>
<property name="map">
<map>
<entry key="country" value="中国"></entry>
<entry key="province" value="上海"></entry>
<entry key="city" value="上海"></entry>
</map>
</property>
<property name="properties">
<props>
<prop key="country">中国</prop>
<prop key="province">上海</prop>
<prop key="city">上海</prop>
</props>
</property>
</bean>
</beans>