简介

介绍

img

发展

img

快速入门

imgimg

Spring配置文件

Bean

img

  • singleton 只有一个 单例

    • 创建时机: 第一行加载配置文件时
  • prototype 多例

    • 创建时机: getBean调用一次 创建一个
1
2
3
4
5
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao1 = (UserDao) app.getBean("userDao");
UserDao userDao2 = (UserDao) app.getBean("userDao");
System.out.println(userDao1); // UserDaoImpl@1c3a4799
System.out.println(userDao2); // UserDaoImpl@1c3a4799

作用范围

img

生命周期

  • 不重要

img

1
2
3
4
<bean id="userDao" class="com.cyt.dao.impl.UserDaoImpl" scope="singleton"
init-method="init" destroy-method="destroy">

</bean>

创建

  • 无参最重要

img

无参

1
2
<bean id="userDao" class="com.cyt.dao.impl.UserDaoImpl"
</bean>

工厂静态

  • 工厂
1
2
3
4
5
public class StaticFactory {
public static UserDao getUserDao() {
return new UserDaoImpl();
}
}
  • 配置文件
1
2
<bean id="userDao" class="com.cyt.factory.StaticFactory" factory-method="getUserDao">
</bean>

工厂实例

  • 工厂 没有static
1
2
3
4
5
public class DynamicFactory {
public UserDao getUserDao() {
return new UserDaoImpl();
}
}
  • 配置文件
1
2
3
<!--创建工厂对象-->
<bean id="factory" class="com.cyt.factory.DynamicFactory"></bean>
<bean id="userDao" factory-bean="factory" factory-method="getUserDao"></bean>

依赖注入

  • 用途 将DAO 注入给Service
1
2
3
<bean id="userService" class="com.cyt.servise.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>

p命名空间

1
2
3
4
xmlns:p="http://www.springframework.org/schema/p"
<bean id="userDao" class="com.cyt.dao.impl.UserDaoImpl">
</bean>
<bean id="userService" class="com.cyt.servise.impl.UserServiceImpl" p:userDao-ref="userDao"/>

构造方法注入

  • 第一个nameuserDao 是构造函数service层参数
  • 第二个 refuserDAO 是容器内部的Bean
1
2
3
4
5
<bean id="userDao" class="com.cyt.dao.impl.UserDaoImpl">
</bean>
<bean id="userService" class="com.cyt.servise.impl.UserServiceImpl">
<constructor-arg name="userDao" ref="userDao"></constructor-arg>
</bean>

注入类型

img

img

  • 集合类型
  • list类型

img

  • map类型

img

  • properties类型

img

img

分模块

img

✨✨相关API

ApplicationContext实现类✨

  • 第二个一般不用
  • 第三个用于注解 在注解开发

img

getBean

img

1
2
3
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao) app.getBean("userDao"); // 用于存在多个bean情况
UserService bean = app.getBean(UserService.class); // 用于一个bean

配置数据源

数据源作用

img

Spring 产生数据源

1
2
3
4
5
6
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:/mysql://localhost:3306/test"></property>
<property name="user" value="root"></property>
<property name="password" value="cyt"></property>
</bean>

img

抽取jdbc配置文件

  • 用于解耦

img

  • jdbc.properties
1
2
3
4
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/cyt_db02
jdbc.username=root
jdbc.password=cyt
  • xml配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?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">

<!--外部加载properties文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>

<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
</beans>

✨✨注解开发

原始注解

  • 5 6 7用于注入

img

案例

  • 配置Dao 实例化Bean
1
2
3
4
5
6
7
8
9
//<bean id="userDao" class="com.cyt.dao.impl.UserDaoImpl"></bean>
//@Component("userDao")
@Repository("userDao") // Dao层 语义明确
public class UserDaoImpl implements UserDao {

public void save() {
System.out.println("save!~");
}
}
  • Service层
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//<bean id="userService" class="com.cyt.service.Impl.UserServiceImpl">
//@Component("userService")
@Service("userService") // Service层 语义明确
public class UserServiceImpl implements UserService {

// <property name="userDao"ref="userDao"></property>
@Autowired // 按照数据类型从Spring容器进行匹配
// @Qualifier("userDao") // 注入Dao 可以省略 只有单个UserDao的bean时
private UserDao userDao;

// public void setUserDao(UserDao userDao) {
// this.userDao = userDao;
// }

public void save() {
userDao.save();
}
}

img

  • 注解扫描

img

1
2
<!--配置组件扫描-->
<context:component-scan base-package="com.cyt"></context:component-scan>

img

其他

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//<bean id="userService" class="com.cyt.service.Impl.UserServiceImpl">
//@Component("userService")
@Service("userService") // Service层 语义明确
@Scope("prototype") // 1 多个
//@Scope("singleton") 单个
public class UserServiceImpl implements UserService {

@Value("${jdbc.driver}")
private String driver;

// <property name="userDao"ref="userDao"></property>
// @Autowired
// @Qualifier("userDao") // 注入Dao 单个bean
@Resource(name = "userDao") // 2 指定id名字 多个bean
private UserDao userDao;

// public void setUserDao(UserDao userDao) {
// this.userDao = userDao;
// }

public void save() {
System.out.println(driver);
userDao.save();
}

@PostConstruct // 3 创建之后
public void init() {
System.out.println("对象创建...");
}
@PreDestroy // 4 销毁之前
public void destroy() {
System.out.println("销毁方法...");
}
}

新注解 AnnotationConfigApplicationContext

原始无法替代

img

新的

img

  • 文件目录

img

  • DataSourceConfiguration分数据源配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//4 <context:property-placeholder location="classpath:jdbc.properties"/>
@PropertySource("classpath:jdbc.properties") // 引入properties配置文件
public class DataSourceConfiguration {
// 5.加载配置
@Value("${jdbc.driver}")
private String driver;

@Value("${jdbc.url}")
private String url;

@Value("${jdbc.username}")
private String username;

@Value("${jdbc.password}")
private String password;


/* <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>*/
@Bean("dataSource") // 3 spring将当前方法的返回值以指定名称id 存到spring容器
// 返回类型DataSource 要放到的容器中
public DataSource geDataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}
}
  • SpringConfiguration 总配置文件
1
2
3
4
5
6
7
8
9
10
//1 标志该类是spring的核心配置类
@Configuration
//2 <context:component-scan base-package="com.cyt"></context:component-scan>
@ComponentScan("com.cyt")
//6 <import resource=""/> 引入分配置文件
@Import({DataSourceConfiguration.class})
public class SpringConfiguration {


}
  • 测试文件
1
2
3
4
5
// ClassPathXmlApplicationContext app = new 
// ClassPathXmlApplicationContext("applicationContext.xml");
ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfiguration.class);
UserService userService = app.getBean(UserService.class);
userService.save();

Spring整合Junit

传统问题

img

步骤

img

  1. 导坐标
1
2
3
4
5
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
  1. 测试文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration("classpath:applicationContext.xml") 配置文件
@ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringJunitTest {
@Autowired
private UserService userService;

@Autowired
private DataSource dataSource;

@Test
public void test() {
userService.save();
}
@Test
public void test1() {
System.out.println(dataSource);
}
}

Spring集成web

环境搭建

  • 自定义工具类 了解 后面spring有专门工具
  1. 导坐标
1
2
3
4
5
6
7
8
9
10
11
12
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.2.1</version>
<scope>provided</scope>
</dependency>
  1. tomcat监听器

img

  1. listener/WebApplicationContextUtils
1
2
3
4
5
public class WebApplicationContextUtils {
public static ApplicationContext getWebApplicationContext(ServletContext servletContext) {
return (ApplicationContext) servletContext.getAttribute("app");
}
}
  1. web/UserSevlet
1
2
3
4
5
6
7
8
9
10
11
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
ServletContext servletContext = this.getServletContext();
//ApplicationContext app = (ApplicationContext) servletContext.getAttribute("app");
ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
UserService userService = app.getBean(UserService.class);
userService.save();
}
}

✨✨Spring获取上下文

img

img

导入依赖

1
2
3
4
5
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>

配置web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="4.0" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd">

<!--初始化全局参数-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>

<!--配置监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>com.cyt.web.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/userServlet</url-pattern>
</servlet-mapping>
</web-app>

web/servlet

1
2
3
4
5
6
7
8
9
10
11
12
13
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
ServletContext servletContext = this.getServletContext();
//ApplicationContext app = (ApplicationContext) servletContext.getAttribute("app");
//ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
ApplicationContext app = WebApplicationContextUtils
.getRequiredWebApplicationContext(servletContext);
UserService userService = app.getBean(UserService.class);
userService.save();
}
}

尚硅谷Spring

手写IOC

img

  • 先配置文件

    • bean表示将类交给容器
    • properties配置依赖 也是后面的DI(依赖注入)
  • 在ClassPathXmlApplicaionContext.java读取xml配置new bean对象并配置依赖

    • 两层for循环
    • img
    • 第一次:遍历bean,取出结点id class
    • img
    • 第二次:遍历每个bean的依赖,取出结点,读取name ref
    • 注入依赖
      • 通过反射,将beanObj和refObj依赖关系绑定
      • img

MVC复习

img

img

IOC和DI

基本介绍

IOC

img

DI

  • 为成员变量赋值
  • ioc是思想,DI是对ioc的一种实现

img

IOC在spring实现

查看关系

img

  • 继承实现关系

img

细节

  • pojo对象一定要有无参构造(含有有参构造时)
  • 不然报错<init>.

获取bean的三种方式

  • 一般用类型获取 class
1
2
3
Student studentOne = (Student) ioc.getBean("studentOne");
Student bean = ioc.getBean(Student.class);
Student studentOne1 = ioc.getBean("studentOne", Student.class);
  • 结论

    • 根据类型来获取bean时,在满足bean唯一性的前提下,其实只是看:『对象 instanceof 指定的类 型』的返回结果,只要返回的是true就可以认定为和类型匹配,能够获取到。
    • 满足这个类 或其父类 或其实现的接口

依赖注入DI

setter注入

  • applicationContext.xml
1
2
3
4
5
6
7
<bean id="studentTwo" class="com.cyt.spring.pojo.Student">
<property name="sid" value="1001"/>
<property name="sname" value="张三"/>
<property name="age" value="23"/>
<property name="gender" value="男"/>
</bean>
// Student{sid=1001, sname='张三', age=23, gender='男'}

构造器注入

1
2
3
4
5
6
<bean id="studentThree" class="com.cyt.spring.pojo.Student">
<constructor-arg value="1002"/>
<constructor-arg value="张三"/>
<constructor-arg value="23"/>
<constructor-arg value="男"/>
</bean>

特殊处理

null

1
2
3
4
5
6
7
8
<bean id="studentTwo" class="com.cyt.spring.pojo.Student">
<property name="sid" value="1001"/>
<property name="sname" value="张三"/>
<property name="age" value="23"/>
<property name="gender">
<null/>
</property>
</bean>

xml实体

  • 代替<>
1
2
3
<!-- 小于号在XML文档中用来定义标签的开始,不能随便使用 -->
<!-- 解决方案一:使用XML实体来代替 -->
<property name="expression" value="&lt;王五&rt;"/>

CDATA

1
2
3
4
5
6
7
<property name="expression">
<!-- 解决方案二:使用CDATA节 -->
<!-- CDATA中的C代表Character,是文本、字符的含义,CDATA就表示纯文本数据 -->
<!-- XML解析器看到CDATA节就知道这里是纯文本,就不会当作XML标签或属性来解析 -->
<!-- 所以CDATA节中写什么符号都随意 -->
<value><![CDATA[a < b]]></value>
</property

✨为类赋值

ref引用

  • student中有clazz属性(类变量)
  • 从IOC容器中已有的bean赋值
1
2
3
4
5
6
7
8
9
10
11
<bean id="studentFive" class="com.cyt.spring.pojo.Student">
<property name="sid" value="1005"/>
<property name="sname" value="张三"/>
<property name="age" value="25"/>
<property name="gender" value="男"/>
<property name="clazz" ref="clazzOne"/>
</bean>
<bean id="clazzOne" class="com.cyt.spring.pojo.Clazz">
<property name="cid" value="1111"/>
<property name="cname" value="1班"/>
</bean>

级联方式

  • 用的不多

img

内部bean

  • 内部bean不能直接通过IOC获取
  • 只能在bean的内部使用
1
2
3
4
5
6
7
8
9
10
11
12
<bean id="studentFive" class="com.cyt.spring.pojo.Student">
<property name="sid" value="1005"/>
<property name="sname" value="张三"/>
<property name="age" value="25"/>
<property name="gender" value="男"/>
<property name="clazz"> 内部
<bean id="clazzInner" class="com.cyt.spring.pojo.Clazz">
<property name="cname" value="2222"/>
<property name="cid" value="2222"/>
</bean>
</property>
</bean>

数组

  • 字面量 用value
  • 对象数组用ref
1
2
3
4
5
6
7
<property name="hobby">
<array>
<value>抽烟</value>
<value>喝酒</value>
<value>烫头</value>
</array>
</property>

list集合

  • private List<Student> students;
  • 方式一
1
2
3
4
5
6
7
8
9
10
11
<bean id="clazzOne" class="com.cyt.spring.pojo.Clazz">
<property name="cid" value="1111"/>
<property name="cname" value="1班"/>
<property name="students">
<list>
<ref bean="studentOne"/> 引用学生类
<ref bean="studentThree"/>
<ref bean="studentFive"/>
</list>
</property>
</bean>
  • 防止二 :直接引用list集合
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<bean id="clazzOne" class="com.cyt.spring.pojo.Clazz">
<property name="cid" value="1111"/>
<property name="cname" value="1班"/>
<!--<property name="students">
<list>
<ref bean="studentOne"/>
<ref bean="studentThree"/>
<ref bean="studentFive"/>
</list>
</property>-->
<property name="students" ref="studentList"/>
</bean>

<!--配置一个集合类型的bean 需要使用util约束-->
<util:list id="studentList">
<ref bean="studentOne"/>
<ref bean="studentTwo"/>
<ref bean="studentFive"/>
</util:list>

map结合

  • private Map<String, Teacher> teacherMap;
  • 法一:引用teacher类 类型
1
2
3
4
5
6
7
8
9
10
11
12
<property name="teacherMap">
<map>
<entry key="111" value-ref="teacherOne"/>
</map>
</property>



<bean id="teacherOne" class="com.cyt.spring.pojo.Teacher">
<property name="tid" value="111"/>
<property name="tname" value="111"/>
</bean>
  • 法二
1
2
3
4
5
<property name="teacherMap" ref="teacherMap"/>

<util:map id="teacherMap">
<entry key="111" value-ref="teacherOne"/>
</util:map>

p命名空间

  • 每个属性都有字面量和ref
1
2
<bean id="studentSix" class="com.cyt.spring.pojo.Student"
p:sid="10065" p:sname="小敏" p:teacherMap-ref="teacherMap"/>

配置数据源

  • spring-datasource.xml
1
2
3
4
5
6
7
8
<!--引入文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
<property name="url" value="${jdbc.url}"/>
</bean>
  • jdbc.properties
1
2
3
4
jdbc.user=root
jdbc.password=cyt
jdbc.url=jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC
jdbc.driver=com.mysql.cj.jdbc.Driver

bean作用域&生命周期

bean的作用域

img

  • spirng创建的bean对象默认是到单例模式
1
2
3
4
5
6
ClassPathXmlApplicationContext ioc = new 
ClassPathXmlApplicationContext("spring-scope.xml");
Student student1 = ioc.getBean(Student.class);
Student student2 = ioc.getBean(Student.class);
System.out.println(student1.hashCode()); // 175408781
System.out.println(student2.hashCode()); // 175408781
  • 如何改为多例

    • scope="prototype"
    • 默认是singleton 一般用的多
1
2
3
4
<bean id="student" class="com.cyt.spring.pojo.Student" scope="prototype">
<property name="sid" value="1001"/>
<property name="sname" value="张三"/>
</bean>

bean生命周期

img

  • ConfigurableApplicationContext 是ApplicationContext的子接口其中扩展了刷新和关闭容器的功能
  • 配置xml
1
2
3
4
5
6
7
8
<bean id="user" class="com.cyt.spring.pojo.User" init-method="initMethod" 
destroy-method="destroyMethod">

<property name="id" value="1"/>
<property name="username" value="admin"/>
<property name="password" value="123456"/>
<property name="age" value="20"/>
</bean>
  • 周期
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public User() {
System.out.println("生命周期:1、创建对象");
}


public void setId(Integer id) {
System.out.println("生命周期:2、依赖注入" + id);
this.id = id;
}

public void initMethod() {
System.out.println("生命周期:3、初始化");
}

4. 使用

public void destroyMethod() {
System.out.println("生命周期:5、销毁");
}
  • 测试
1
2
3
4
5
6
7
@Test
public void test() {
ConfigurableApplicationContext ioc = new ClassPathXmlApplicationContext("spring-lifecycle.xml");
User user = ioc.getBean(User.class);
System.out.println(user);
ioc.close();
}

作用域对生命周期影响

img

bean的后置处理器

  • bean的后置处理器会在生命周期的初始化前后添加额外的操作,需要实现BeanPostProcessor接口, 且配置到IOC容器中,需要注意的是,bean后置处理器不是单独针对某一个bean生效,而是针对IOC容 器中所有bean都会执行
  • 生命周期(all)
  • img
  • process.MyBeanPostProcessor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class MyBeanPostProcessor implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
// 此方法在bean的生命周期初始化之前执行
System.out.println("before");
return bean;
}

public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
// 此方法在bean的生命周期初始化之后执行
System.out.println("after");
return bean;
}
}

// 生命周期:1、创建对象
// 生命周期:2、依赖注入1
// before
// 生命周期:3、初始化
// after
// User{id=1, username='admin', password='123456', age=20}
// 生命周期:5、销毁

FactoryBean

  • 工厂bean,和之前的bean工厂不同(bean工厂是内置的)

  • 以前的工厂对象

    • 先获取工厂对象
    • 再得到工厂提供的对象
  • 现在:

    • 直接获取工厂对象里的对象
  • FactoryBean是Spring提供的一种整合第三方框架的常用机制。和普通的bean不同,配置一个 FactoryBean类型的bean,在获取bean的时候得到的并不是class属性中配置的这个类的对象,而是 getObject()方法的返回值。通过这种机制,Spring可以帮我们把复杂组件创建的详细过程和繁琐细节都 屏蔽起来,只把最简洁的使用界面展示给我们。

img

  • factory.UserFactoryBean
1
2
3
4
5
6
7
8
9
public class UserFactoryBean implements FactoryBean<User> {
public User getObject() throws Exception {
return new User();
}

public Class<?> getObjectType() {
return User.class;
}
}
  • 配置xml
1
<bean class="com.cyt.spring.factory.UserFactoryBean"/>

自动装配

模拟

  • controller 调用 service层
  • service 调用Dao层
  • xml配置
1
2
3
4
5
6
7
8
9
<bean id="userDao" class="com.cyt.spring.dao.impl.UserDaoImpl"></bean>

<bean id="userService" class="com.cyt.spring.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"/>
</bean>

<bean class="com.cyt.spring.controller.UserController">
<property name="userService" ref="userService"/>
</bean>
  • 测试装配
1
2
3
4
5
6
7
8
public class AutowireByXMLTest {
@Test
public void test() {
ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("spring-autowire.xml");
UserController userController = ioc.getBean(UserController.class);
userController.saveUser();
}
}

自动装配

img

byType

  • autowire="byType"适用于该类型只有一个bean
  • byName 适用于有多个bean
1
2
3
4
5
6
7
8
9
<bean id="userDao" class="com.cyt.spring.dao.impl.UserDaoImpl"></bean>
<bean id="userService" class="com.cyt.spring.service.impl.UserServiceImpl"
autowire="byType">
<!-- <property name="userDao" ref="userDao"/>-->
</bean>

<bean class="com.cyt.spring.controller.UserController" autowire="byType">
<!-- <property name="userService" ref="userService"/>-->
</bean>

byName

img

  • id名 = 待配置的属性名
1
2
3
4
5
6
7
8
9
10
11
<bean id="userDao" class="com.cyt.spring.dao.impl.UserDaoImpl"></bean>
<bean id="userService" class="com.cyt.spring.service.impl.UserServiceImpl" autowire="byType">
<!-- <property name="userDao" ref="userDao"/>-->
</bean>
<bean id="Service" class="com.cyt.spring.service.impl.UserServiceImpl" autowire="byType">
<!-- <property name="userDao" ref="userDao"/>-->
</bean>

<bean class="com.cyt.spring.controller.UserController" autowire="byName"> name
<!-- <property name="userService" ref="userService"/>-->
</bean>

✨注解开发

标识组件常用注解

  • 四个没有区别

    • 只是为了分辨组件作用

img

  • controller
1
2
3
@Controller
public class UserController {
}
  • service
1
2
3
@Service
public class UserServiceImpl implements UserService {
}
  • Dao
1
2
3
@Repository
public class UserDaoImpl implements UserDao {
}

扫描

1
2
<!--扫描组件-->
<context:component-scan base-package="com.cyt.spring"/>
  • spring整合时

    • spring-mvc扫描控制层controller
    • spring扫描除了控制层以外

包含排除

  • 排除(包含同理)
1
2
3
4
5
6
7
8
9
<!--扫描组件-->
<context:component-scan base-package="com.cyt.spring">
<!--不扫瞄控制层 根据注解类型排除-->
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
<!--不扫瞄 根据类名排除-->
<context:exclude-filter type="assignable"
expression="com.cyt.spring.controller.UserController"/>
</context:component-scan>
  • 包含(只包含)

  • 用得少 一般直接指定具体的包

    • 默认使用true(扫描所有)
    • 修改为use-default-filters="false"
    • 再配置只扫描类型
1
2
3
4
5
6
7
8
9
<!--扫描组件-->
<context:component-scan base-package="com.cyt.spring" use-default-filters="false">
<!--不扫瞄控制层 根据注解类型排除-->
<!-- <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>-->
<!--不扫瞄 根据类名排除-->
<!-- <context:exclude-filter type="assignable" expression="com.cyt.spring.controller.UserController"/>-->
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

bean的id

  • 默认为第一个字母 小写

在我们使用XML方式管理bean的时候,每个bean都有一个唯一标识,便于在其他地方引用。现在使用 注解后,每个组件仍然应该有一个唯一标识

  • 默认情况 :类名首字母小写就是bean的id。例如:UserController类对应的bean的id就是userController。 自定义bean的id

  • 可通过标识组件的注解的value属性设置自定义的bean的id @Service("userService")//默认为userServiceImpl public class UserServiceImpl implements UserService {}

  • 配置别名

1
2
3
@Controller("controller")
public class UserController {
}

@Autowired自动装配

使用

  • controller
1
2
@Autowired
private UserService userService;
  • Service
1
2
@Autowired
private UserDao userDao;

细节

img

原理

img

img

img

1
2
3
@Autowired
@Qualifier("userServiceImpl")
private UserService userService;

==AOP==

代理模式

img

理解

img

动态代理

img

JDK动态代理

  • 计算类(目标类)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class CalculatorImpl implements Calculator {
public int add(int i, int j) {
int result = i + j;
System.out.println("方法内部,result:" + result);
return result;
}

public int sub(int i, int j) {
int result = i - j;
System.out.println("方法内部,result:" + result);
return result;
}

public int mul(int i, int j) {
int result = i * j;
System.out.println("方法内部,result:" + result);
return result;
}

public int div(int i, int j) {
int result = i / j;
System.out.println("方法内部,result:" + result);
return result;
}
}
  • 工厂函数 生成任意目标类的代理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class ProxyFactory {
private Object target;

public ProxyFactory(Object target) {
this.target = target;
}

public Object getProxy() {
ClassLoader classLoader = this.getClass().getClassLoader();
Class<?>[] interfaces = target.getClass().getInterfaces();
InvocationHandler h = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
try {
System.out.println("日志,方法:" + method.getName() + ",参数:" + Arrays.toString(args));
// proxy表示代理对象 method表示要执行的方法 args表示要执行方法的参数列表
result = method.invoke(target, args);
System.out.println("日志,方法:" + method.getName() + ",结果:" + result);
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("日志,方法:" + method.getName() + "方法执行完毕");
}
return result;
}
};
/*
newProxyInstance():创建一个代理实例
其中有三个参数:
1、classLoader:加载动态生成的代理类的类加载器
2、interfaces:目标对象实现的所有接口的class对象所组成的数组
3、invocationHandler:设置代理对象实现目标对象方法的过程,即代理类中如何重写接
口中的抽象方法
*/
return Proxy.newProxyInstance(classLoader, interfaces, h);
}
}
  • 测试方法
1
2
3
4
5
6
7
8
@Test
public void testProxy() {
ProxyFactory proxyFactory = new ProxyFactory(new CalculatorImpl());
// 该类动态代理创建 类型不确定$proxy 可以用接口接收
Calculator proxy = (Calculator) proxyFactory.getProxy();
proxy.add(1, 2);
proxy.div(1, 0);
}

Aop相关术语

横切关注点

  • 非核心方法

    • 对于目标方法而言
    • (有哪些方法名)
    • (抽取前代码的部分源代码)

img

通知

  • 非核心方法

    • 对于切面来说
    • (为上面方法名编写方法)

img

切面

  • 封装通知方法的类
  • (为上面编写的方法封装成类)

img

目标&代理&连接点

  • 目标:非核心业务
  • 代理:代理后的目标
  • 连接点:不是代码层面的(下面切入点是)

img

切入点

img

总结

  • 面向切面关键:

    • 抽取横切关注点(方法名)
    • 封装到切面中(类)
    • 编写通知(方法)
    • 用切入点表达式(代码层面)定位到连接点(逻辑层面)
    • 最终功能增强

基于注解

导入依赖

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.3.1</version>
</dependency>

创建切面类

  • 注意:切面类必须通过@Aspect注解标识
1
2
3
4
5
6
7
8
9
@Component
@Aspect // 标识组件为切面
public class LoggerAspect {

@Before("execution(public int com.cyt.spring.aop.annotation.CalculatorImpl.add(int,int))")
public void beforeAdviceMethod() {
System.out.println("LoggerAspect,前置通知");
}
}

IOC容器管理

  • 注意:AOP中,切面类和目标类都要交给IOC管理
1
2
3
<context:component-scan base-package="com.cyt.spring.aop.annotation"/>
<!--开启基于注解的AOP-->
<aop:aspectj-autoproxy/>

测试

1
2
3
4
5
6
7
@Test
public void testAopByAnnotation() {
ClassPathXmlApplicationContext ioc = new
ClassPathXmlApplicationContext("aop-annotation.xml");
Calculator caculator = ioc.getBean(Calculator.class);
caculator.add(1,1);
}

切入点表达式

四个通知

  • LoggerAspect,前置通知 add 执行完毕
  • 方法内部,result:2
  • LoggerAspect,返回通知 add 执行完毕 结果:2
  • LoggerAspect,后置通知 add 执行完毕
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
@Component
@Aspect // 标识组件为切面
public class LoggerAspect {

/*切入点表达式重用*/
@Pointcut("execution(* com.cyt.spring.aop.annotation.*.*(..))")
public void pointcut() {
}

//@Before("execution(public int com.cyt.spring.aop.annotation.
// CalculatorImpl.add(int,int))")
@Before("execution(* com.cyt.spring.aop.annotation.*.*(..))")
public void beforeAdviceMethod(JoinPoint joinPoint) {
// 获取签名信息
Signature signature = joinPoint.getSignature();
//System.out.println(signature.getName()); // 方法名 add
//System.out.println(Arrays.toString(joinPoint.getArgs())); // [1, 1]
System.out.println("LoggerAspect,前置通知 " + signature.getName() + " 执行完毕");
}

// 返回通知
// 获取目标对象的返回值 returning = "result" ,Object result
@AfterReturning(value = "pointcut()", returning = "result")
public void afterReturningAdviceMethod(JoinPoint joinPoint, Object result) {
Signature signature = joinPoint.getSignature();
System.out.println("LoggerAspect,返回通知 " + signature.getName() +
" 执行完毕" + " 结果:" + result);
}

// 后置通知
@After("pointcut()")
public void afterAdviceMethod(JoinPoint joinPoint) {
Signature signature = joinPoint.getSignature();
System.out.println("LoggerAspect,后置通知 " + signature.getName() + " 执行完毕");
}

// 异常通知 获取异常 throwing = "ex" Throwable ex
@AfterThrowing(value = "pointcut()", throwing = "ex")
public void AfterThrowingAdviceMethod(JoinPoint joinPoint,Throwable ex) {
Signature signature = joinPoint.getSignature();
System.out.println("LoggerAspect,异常通知 " +
signature.getName() + " 执行完毕 异常:" + ex);
}
}

执行顺序

img

环绕通知

  • ProceedingJoinPoint可执行连接点
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Around("pointcut()")
public Object aroundAdviceMethod(ProceedingJoinPoint joinPoint) {
Object result = null;
try {
System.out.println("环绕通知--前置通知");
// 表示目标方法的执行
result = joinPoint.proceed();
System.out.println("环绕通知--返回通知");
} catch (Throwable e) {
e.printStackTrace();
System.out.println("环绕通知--异常通知");
} finally {
System.out.println("环绕通知--后置通知");
}
return result;
}
  • 顺序

img

优先级

  • @Order(1)
1
2
3
4
5
6
7
8
9
10
11
@Component
@Aspect
@Order(1)
public class ValidateAspect {

//@Before("execution(* com.cyt.spring.aop.annotation.*.*(..))")
@Before("com.cyt.spring.aop.annotation.LoggerAspect.pointcut()")
public void beforeMethod() {
System.out.println("ValidateAspect---前置通知");
}
}

xml开发

  • 了解
1
2
3
4
5
6
7
8
9
10
11
12
13
<!--配置目标对象-->
<bean id="target" class="com.cyt.proxy.aop.Target"></bean>
<!--配置切面对象-->
<bean id="myAspect" class="com.cyt.proxy.aop.MyAspect"></bean>
<!--配置织入 告诉spring 那些方法需要那些增强(前置,后置)-->
<aop:config>
<!--声明切面-->
<aop:aspect ref="myAspect">
<!--切面: 切点 + 通知 --> 切点表达式
<aop:before method="before" pointcut="execution(public void com.cyt.proxy.aop.
Target.save())"/>
</aop:aspect>
</aop:config>