一、Spring
(学框架不要以为很难,框架做出来就给你用的,就是用来快速开发的、简化代码的,学框架主要是学习如何配置框架即如何搭建框架环境,其次再是如何使用!当然学好框架能让你写代码更上一层楼)
1、Spring概念
1.Spring是轻量级的开源的JavaEE框架
2.Spring可以解决企业应用开发的复杂性
3.Spring有两个核心部分:IOC和Aop
( 1) IOC:控制反转,把创建对象过程交给Spring进行管理
(2)Aop:面向切面,不修改源代码进行功能增强
4.Spring的特点
(1)方便解耦,简化开发(2) Aop编程支持
(3)方便程序测试s
(4)方便和其他框架进行整合。(5)方便进行事务操作
(6)降低API开发难度。
spring基础例子
创一个user类
public class User {
public void add(){
System.out.println("add...");
}
}
创建bean1.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">
<!--配置User对象创建-->
<!--
id : 别名
class : 是目标类的路径
-->
<bean id="user" class="spring5.User"/>
</beans>
用test方法进行测试
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import spring5.User;
public class TestSpring5 {
@Test
public void testAdd(){
//1加载spring配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
//2获取配置创建的对象
User user = context.getBean("user", User.class);
System.out.println(user);
user.add();
}
}
2、IOC容器
1、什么是IOC
(1)控制反转,把对象创建和对象之间的调用过程,交给Spring进行管理
(2)使用IOC目的:为了耦合度降低。
(3)做入门案例就是IOC实现
2、IOC底层原理
(1) xml解析、工厂模式、反射
(什么是反射?通过得到类的字节码文件进而操作类中所有内容)
IOC接口
1、IOC思想基于IOC容器完成,IOC容器底层就是对象工厂
2、Spring提供IOC容器实现两种方式:(两个接口)
(1) BeanFactory:IOC容器基本实现,是Spring内部的使用接口,不提供,开发人员使用
加载配置获取文件时候不会创建对象,在获取对象(使用)才去创建对象
(2)ApplicationContext:BeanFactory接口的子接口,提供更更多更强大的功能,一般由开发人员进行使用
加载配置文件时候就会把在配置文件对象进行创建
(3)ApplicationContext接口有实现类
3、IOC操作Bean管理
1、什么是Bean管理
(0)Bean管理指的是两个操作
(1) Spring创建对象
(2)Spirng,注入属性
2、Bean管理操作有两种方式
(1)基于xml配置文件方式实现
<!--配置User对象创建-->
<!--
id : 别名
class : 是目标类的路径
-->
<bean id="user" class="spring5.User"/>
(1.1)在spring配置文件中,使用bean标签,标签里面添加对应属性,就可以实现对象创建
(1.2)在bean标签有很多属性,介绍常用的属性
id属性:唯一标识
class属性:类全路径(包类路径)
(1.3)创建对象时候,默认也是执行无参数构造方法完成对象的创建
(2)基于xml注解方式实现
(1)DI:依赖注入,就是注入属性
第一种注入方式:使用set方法进行注入
<!--set方法注入属性-->
<bean id="book" class="spring5.Book">
<property name="name" value="java"/>
<property name="author" value="jan"/>
</bean>
第二种注入方式:使用有参数构造进行注入
<!--有参构造注入属性-->
<bean id="orders" class="spring5.Orders">
<constructor-arg name="name" value="电脑"></constructor-arg>
<constructor-arg name="address" value="guangdong"></constructor-arg>
</bean>
(3) p名称空间注入
(1)使用p名称空间注入,可以简化基于xml配置方式
xmlns:p="http://www.springframework.org/schema/p"
(2)注入属性
<!--set方法注入属性-->
<bean id="book" class="spring5.Book" p:name="java" p:author="tom">
</bean>
3、注入外部属性-外部bean
(1)创建两个类service类和dao类
(2)在service 调用dao里面的方法
(3)在spring配置文件中进行配置
3.2、注入属性-内部bean和级联赋值
内部bean
package bean;
//部门类
public class Dept {
private String name;
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Dept{" +
"name='" + name + '\'' +
'}';
}
}
package bean;
//员工类
public class Emp {
private String name;
private String gender;
//员工属于某一个部门
private Dept dept;
public void setDept(Dept dept) {
this.dept = dept;
}
public void setName(String name) {
this.name = name;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Emp{" +
"name='" + name + '\'' +
", gender='" + gender + '\'' +
", dept=" + dept +
'}';
}
}
<?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-->
<bean id="emp" class="bean.Emp">
<!--设置两个普通属性-->
<property name="name" value="jan"/>
<property name="gender" value="女"/>
<!--设置对象类型属性-->
<property name="dept">
<bean id="dept" class="bean.Dept">
<property name="name" value="IT"/>
</bean>
</property>
</bean>
</beans>
@Test
public void test2(){
//1加载spring配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("bean3.xml");
//2获取配置创建的对象
Emp emp = context.getBean("emp", Emp.class);
System.out.println(emp);
}
级联赋值
<?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="emp" class="bean.Emp">
<!--设置两个普通属性-->
<property name="name" value="jan"/>
<property name="gender" value="女"/>
<!--级联赋值-->
<property name="dept" ref="dept"/>
</bean>
<bean id="dept" class="bean.Dept">
<property name="name" value="IT"></property>
</bean>
</beans>
4、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">
<!--list集合类型属性在注入-->
<bean id="stu" class="collectiontype.Stu">
<!--数组类型属性注入-->
<property name="courses">
<array>
<value>java</value>
<value>js</value>
</array>
</property>
<!--list类型属性注入-->
<property name="list">
<list>
<value>张三</value>
<value>李四</value>
</list>
</property>
<!--map类型属性注入-->
<property name="maps">
<map>
<entry key="JAVA" value="java"/>
<entry key="JS" value="js"/>
</map>
</property>
<!--set类型属性注入-->
<property name="sets">
<set>
<value>Mysql</value>
<value>Redis</value>
</set>
</property>
</bean>
</beans>
在集合里面设置对象类型值(注入多个值)
新增Crouse类
package collectiontype;
public class Crouse {
private String name;
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Crouse{" +
"name='" + name + '\'' +
'}';
}
}
Stu类添加代码
//课程
private List<Crouse> crouseList;
public void setCrouseList(List<Crouse> crouseList) {
this.crouseList = crouseList;
}
xml配置
<!--创建多个course对象-->
<bean id="course1" class="collectiontype.Crouse">
<property name="name" value="spring5"/>
</bean>
<bean id="course2" class="collectiontype.Crouse">
<property name="name" value="mybatis"/>
</bean>
<!--注入list集合类型,值是对象-->
<property name="crouseList">
<list>
<ref bean="course1"></ref>
<ref bean="course2"></ref>
</list>
</property>
注入集合属性2(util标签)
package collectiontype;
import java.util.List;
public class Book {
private List<String> list;
public void setList(List<String> list) {
this.list = list;
}
@Override
public String toString() {
return "Book{" +
"list=" + list +
'}';
}
}
xml文件,添加util名称
<?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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!--提取list集合类型属性注入-->
<util:list id="booklist">
<value>java</value>
<value>js</value>
<value>c++</value>
</util:list>
<!--注入使用-->
<bean id="book" class="collectiontype.Book">
<property name="list" ref="booklist"/>
</bean>
</beans>
5、工厂bean
实现FactoryBean接口
package factorybean;
import collectiontype.Crouse;
import org.springframework.beans.factory.FactoryBean;
public class MyBean implements FactoryBean<Crouse> {
/**
* 返回bean
* @return
* @throws Exception
*/
@Override
public Crouse getObject() throws Exception {
Crouse crouse = new Crouse();
crouse.setName("abc");
return crouse;
}
@Override
public Class<?> getObjectType() {
return null;
}
@Override
public boolean isSingleton() {
return false;
}
}
配置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="myBean" class="factorybean.MyBean">
</bean>
</beans>
测试类
@Test
public void test3(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean3.xml");
//此处不再用myBean.class,而是改为需要返回的类的类名
Crouse crouse = context.getBean("myBean", Crouse.class);
System.out.println(crouse);
}
6、bean作用域
1.在Spring里面,默认情况下, bean是单实例对象
(单实例对象:同一对象获取多次并输出地址是一样的)
2.在spring配置文件 bean标签里面有属性(scope)用于设置单实例还是多实例(原型)
scope属性值
第一个值默认值,singleton,表示是单实例对象(默认)
第二个值prototype,表示是多实例对象
7、bean生命周期
(1) 通过构造器创建bean实例(无参数构造)
(2) 为bean的属性设置值和对其他 bean引用(调用set方法)
(3) 调用bean的初始化的方法(需要进行配置初始化的方法)
(4) bean可以使用了(对象获取到了)
(5) 当容器关闭时候,调用bean 的销毁的方法(需要进行配置销毁的方法)
演示:
package bean;
public class Orders {
private String name;
public Orders() {
System.out.println("1.执行无参构造创建bean实例");
}
public void setName(String name) {
this.name = name;
System.out.println("2.调用set方法,设置属性值");
}
//创建执行初始化方法
public void initMethod(){
System.out.println("3.执行初始化方法");
}
public void destoryMethod(){
System.out.println("5.执行销毁方法");
}
@Override
public String toString() {
return "Orders{" +
"name='" + name + '\'' +
'}';
}
}
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="orders" class="bean.Orders" init-method="initMethod" destroy-method="destoryMethod">
<property name="name" value="phone"/>
</bean>
</beans>`
@Test
public void test4(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean4.xml");
//此处不再用myBean.class,而是改为需要返回的类的类名
Orders orders = context.getBean("orders", Orders.class);
System.out.println("4.获取创建bean实例对象");
System.out.println(orders);
//手动销毁
context.close();
}
结果:
1.执行无参构造创建bean实例
2.调用set方法,设置属性值
3.执行初始化方法
4.获取创建bean实例对象
Orders{name='phone'}
5.执行销毁方法
但其实一共有七步
(1) 通过构造器创建bean实例(无参数构造)
(2) 为bean的属性设置值和对其他 bean引用(调用set方法)
bean实例传递给bean后置处理器postProcessBeforeInitialization
(3) 调用bean的初始化的方法(需要进行配置初始化的方法)
bean实例传递给bean后置处理器postProcessAfterInitialization
(4) bean可以使用了(对象获取到了)
(5) 当容器关闭时候,调用bean 的销毁的方法(需要进行配置销毁的方法)
那么后置处理如何体现?用一个类去实现接口BeanPostProcessor然后重写里面的方法再用xml文件去配置bean标签
package bean;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class MyBeanPost implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("在初始化之前执行的方法");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("在初始化之后执行的方法");
return bean;
}
}
xml配置新增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">
<bean id="orders" class="bean.Orders" init-method="initMethod" destroy-method="destoryMethod">
<property name="name" value="phone"/>
</bean>
<bean id="myBeanPost" class="bean.MyBeanPost"/>
</beans>
执行结果
1.执行无参构造创建bean实例
2.调用set方法,设置属性值
在初始化之前执行的方法
3.执行初始化方法
在初始化之后执行的方法
4.获取创建bean实例对象
Orders{name='phone'}
5.执行销毁方法
7、bean管理xml文件方式
1、自动装配
<?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标签属性autowire,配置自动装配
autowire属性常用两个值:
byName根据属性名称注入,注入值bean的id值和类属性名称一样
byType根据属性类型注入
-->
<bean id="emp" class="autowire.Emp" autowire="byName">
<!--<property name="dept" ref="dept"/>-->
</bean>
<bean id="dept" class="autowire.Dept"/>
</beans>
2、外部属性
以引入jdbc配置为例
jdbc.properties
driverClass="com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/userDb
username=root
password=123
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">
<!--直接配置连接池-->
<!--<bean id="" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/userDb"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
</bean>-->
<!--引入外部属性文件配置数据库连接池-->
<context:property-placeholder location="jdbc.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${driverClass}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</bean>
</beans>
8、bean管理基于注解方式
1、什么是注解
(1)注解是代码特殊标记,格式:@注解名称(属性名称=属性值,属性名称=属性值…)"(2) 使用注解,注解作用在类上面,方法上面,属性上面·
(3)使用注解目的:简化xml配置
2、Spring对于Bean管理中创建对象提供注解
(1)@Component
(2)@Service ----service层
(3)@Controller. ----web层
(4)@Repositorye ----dao层
上面4个注解功能都是一样的,都可以用来创建bean实例
package service;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
/*
在注解里面value属性值可以省不写
默认值是类名称,首字母小写 UserService-userSerice
*/
@Service
public class UserService {
public void add(){
System.out.println("service add...");
}
}
开启扫描
<?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">
<!--开启组件扫描-->
<!--
1 如果要扫描多个包,多个包使用逗号隔开
2 扫描包上层目录
-->
<context:component-scan base-package="dao,service"/>
</beans>
测试方法
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
UserService userService = context.getBean("userService", UserService.class);
System.out.println(userService);
userService.add();
}
注解实例,需要看懂!
<?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">
<!--开启组件扫描-->
<!--
1 如果要扫描多个包,多个包使用逗号隔开
2 扫描包上层目录
-->
<context:component-scan base-package="dao,service"/>
<!--示例1
use-default-filters="false" 表示自己配置filter
context:include-filter 设置需要扫描的内容
expression 表示当前包只扫描Controller注解相关内容,不扫描其他的
-->
<context:component-scan base-package="dao,service" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--实例2
use-default-filters="false" 表示自己配置filter
context:exclude-filter 表示不扫描的内容
expression 表示当前包不扫描Controller注解相关内容,扫描其他的
-->
<context:component-scan base-package="dao,service" use-default-filters="false">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
3、基于注解方式实现属性注入
(1)@AutoWired 根据属性类型进行自动装配
第一步把 service和dao对象创建,在service和dao类添加创建对象注解
package dao;
public interface UserDao {
public void add();
}
package dao.Impl;
import dao.UserDao;
import org.springframework.stereotype.Repository;
@Repository
public class UserDaoImpl implements UserDao {
@Override
public void add() {
System.out.println("dao add...");
}
}
第二步在service注入 dao对象,在service类添加dao类型属性,在属性上面使用注解
package service;
import dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
/*
在注解里面value属性值可以省不写
默认值是类名称,首字母小写 UserService-userSerice
*/
@Service
public class UserService {
//定义dao类型属性
//不需要添加set方法
//添加注入属性注解
@Autowired
private UserDao userDao;
public void add(){
System.out.println("service add...");
userDao.add();
}
}
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
UserService userService = context.getBean("userService", UserService.class);
System.out.println(userService);
userService.add();
}
(2)@Qualifier 根据属性名称进行注入
// @Autowired
// @Qualifier
// private UserDao userDao;
要配合Autowired使用
@Qualifier限定哪个bean应该被自动注入。当Spring无法判断出哪个bean应该被注入时,@Qualifier注解有助于消除歧义bean的自动注入。
(3)@Resource 可以根据类型注入,可以根据名称注入
注意点:Resource是javax包下的(即扩展包)不是spring本身自带的(主要问题在于与jdk的兼容,貌似jdk新版本用不了Resource),而且官方也推荐使用Autowried,当然功能是一样的
// @Resource //根据类型注入
@Resource(name = "userDaoImpl")//根据名称注入
private UserDao userDao;
public void add(){
System.out.println("service add...");
userDao.add();
}
(4)@value 注入普通类型属性
package service;
import dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/*
在注解里面value属性值可以省不写
默认值是类名称,首字母小写 UserService-userSerice
*/
@Service
public class UserService {
//定义dao类型属性
//不需要添加set方法
//添加注入属性注解
// @Autowired
// @Qualifier
// private UserDao userDao;
@Value(value = "abc")
private String name;
// @Resource //根据类型注入
@Resource(name = "userDaoImpl")//根据名称注入
private UserDao userDao;
public void add(){
System.out.println("service add..." + name);
userDao.add();
}
}
service.UserService@47b92
service add...abc
dao add...
说明@Value是可以注入普通类型属性的
4、完全注解开发
创建一个配置类,替代xml文件,添加@Configuration和@ComponentScan(basePacks = {“包所在路径”}),然后在测试类中new AnnotationConfigApplicationContext(配置类.class),其他不变,看上面例子
3、Aop
3.1、什么是AOP
(1)面向切面编程(方面),利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
(2)通俗描述:不通过修改源代码方式,在主干功能里面添加新功能
3.2、AOP底层原理
一、有接口的情况,使用JDK动态代理:
创建接口实现类代理对象,增强类的方法
二、没有接口情况,使用CGLIB动态代理:
创建子类的代理对象,增强类的方法(继承)
3.3AOP(动态代理)
1.调用newProxyInstance方法
方法有三个参数:
第一参数,类加载器
第二参数,增强方法所在的类,这个类实现的接口,支持多个接口
第三参数,实现这个接口InvocationHandler,创建代理对象,写增强的方法
3.4 AOP术语
1、连接点:
可以被增强的方法称连接点
2、切入点
实际被真正增强的方法,称为切入点
3、通知(或增强)
1.实际增强的逻辑部分称为通知(增强)
2.通知有多种类型:
*前置通知
*后置通知
*环绕通知
*异常通知
*最终通知(finally)
4、切面
把通知应用到切入点过程
3.5 AOP操作
1、Spring框架一般都是基于Aspectt.实现AOP操作
(1)什么是 AspectJ:
AspectJ不是Spring组成部分,独立AOP框架,一般把Aspect.和Spimg,框架一起使用,进行AOP操作
2、基于Aspect]实现AOP操作
(1)基于xml配置文件实现
(2)基于注解方式实现
3、引入AOP相关依赖
4、切入点表达式
(1)切入点表达式作用:知道对哪个类里面的哪个方法进行增强
(2)语法结构
3.6 AOP操作-AspectJ注解
3.7 AOP操作-AspectJ配置文件
4、jdbcTemplate
这部分就不需要了,直接奔mybatis,远古的东西,了解一下即可
5、事务管理
5.1、什么是事务
(1)事务是数据库操作最基本单元,逻辑上一组操作,要么都成功,如果有一个失败所有操作都失败
(2)典型场景:银行转账
5.2、事务四个特性(ACID )
(1)原子性
(2)一致性
(3)隔离性
(4)持久性
5.3、事务管理介绍
1、事务添加到JaxaEE三层结构里面Service层(业务逻辑层)
2、在 Spring进行事务管理操作
(1) 有两种方式:编程式事务管理和声明式事务管理(使用)
3、声明式事务管理
(1) 基于注解方式
(2) 基于xml配置文件方式
4、spring声明事务管理,底层使用AOP
5.4 注解方式事务管理(处理异常,回滚数据)
1.引入tx空间名称
xmlns:tx="http://www.springframework.org/schema/tx"
http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd
2.创建事务管理器
<!--创建事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
3.Service层添加注解 @Transactional
这样就是spring封装好的事务管理处理方式。我们就不再需要像以前那样try-catch
5.5 声明式事务管理参数配置
1、@Transactional,这个注解里面可以配置事务相关参数
2、propagation:事务传播行为
@Transactional
public void add(){
update();
}
public void add(){
}
REQUIRED
如果add方法本身有事务,调用update方法之后,update使用当前add方法里面事务如果add方法本身没有事务,调用update方法之后,创建新事务
REQUIRED_NEW
使用add方法调用update方法,如果add无论是否有事务,都创建新的事务
3、isolation:事务隔离级别
(1)事务有特性成为隔离性,多事务操作之间不会产生影响。不考虑隔离性产生很多问题
(2)有三个读问题:脏读、不可重复读、虚(幻)读
脏读:一个未提交事务读取到另一个未提交事务的数据
举例:
a、b开启事务
a:查询为100元
b:我要增加到200元,但我没提交
a:查询为200元
不可重复读:是指一个事务范围内,多次查询某个数据,却得到不同的结果
举例
a、b开启事务
a:查询为100元
b:我要增加到200元,还没提交
a:查询为100元
b:我提交事务
a:查询为200元
幻读:一个未提交事务读取到另一个提交事务添加数据
4、timeout:超时时间
(1)事务需要在一定时间内进行提交,如果不提交进行回滚
(2)默认值是-1,设置时间以秒单位进行计算
5、readOnly:是否只读
(1)读:查询操作,写:添加修改删除操作。
(2) readOnly,默认值false,表示可以查询,可以添加修改删除操作
(3)设置readOnly值是true,设置成true之后,只能查询
6、rollbackFor:回滚
7、noRollbackFor:不会滚
6、Spring5特性
二、SpringMVC
1、SpringMVC的概念和理解:
spring mvc是基于spring的一个框架,实际上就是spring的一个模块,专门用于做web开发,可以理解为servlet的一个升级
1.1、我们要做的是使用@Contorller创建控制器对象,把对象放入到springmvc容器中,把创建的对象作为控制器使用这个控制器对象能接收用户的请求,显示处理结果,就当做是一个servlet使用。
使用@controller注解创建的是一个普通类的对象,不是servlet。springmvc赋予了控制器对象一些额外的功能。
1.2、web开发底层是servlet,springmvc中有一个对象是servlet : DispatherServlet(中央调度器)
DispatherServlet:负责接收用户的所有请求,用户把请求给了DispatherServlet,之后Dispatherservlet把请求转发给
我们的controller对象,最后是controller对象处理请求。
2、springmvc请求的处理流程
1)发起some .do
2) tomcat(web. xml–url-pattern知道*.do的请求给DispatcherServlet)
3) DispatcherServlet(根据springmvc.xml配置知道some. do—doSome()
4) Dispatcherservlet把some.do转发个MyController.doSome()方法
5)框架执行doSome() 把得到ModelAndView进行处理
3、springmvc执行过程源代码分析
1.tomcat启动,创建容器的过程
通过load-on-start标签指定的1,创建Disaptcherservlet对象,
Disaptcherservlet它的父类是继承Httpservlet的,它是一个serlvet,在被创建时,会执行init() 方法。在init(方法中
/l创建容器,读取配置文件
webApplicationContext ctx = new classPathXmlApplicationContext ( “springmvc.xm1”);
//把容器对象放入到servletContext中
getservletContext () .setAttribute (key , ctx) ;
上面创建容器作用:创建@Cortroller注解所在的类的对象,创建MyController对象,
这个对象放入到 springmvc的容器中,容器是map ,类似map.put (“myController” ,MyController对象)
三、mybatis
作用:增强的jdbc,访问数据库,执行增删改查操作
基本步骤:
1.加入MAVEN的 依赖
<!--mybatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
</dependencies>
2.创建Dao接口:定义你操作数据的方法
3.创建mapper文件,也叫sql映射文件:写sql语句的,和接口中方法对应得sql语句
4.创建mybatis的一个主配置文件:
1)连接数据库;
2)指定mapper文件的位置
5.使用mybatis的对象SqlSession,通过他的方法执行sql语句
使用mybatis的动态代理
1.什么是动态代理:
mybatis帮你创建dao接口的实现美,在实现类中调用SqlSession的方法执行sql语句
2.使用动态代理的方式:
1):获取SqlSession对象,SqlSessionFactory.openSession0
2):使用getMapper方法获取某个接口的对象,sqlSession.getMapper(接口.class)
3):使用dao接口的方法,调用方法就执行了mapper文件中的sql语句
3.使用动态代理方式的要求
1):dao接口的mapper文件放在一起,同一个目录
2):dao接口和mapper文件名称一致
3):mapper文件的namespace的值是dao接口的全限定名称
4):mapper文件中的,,,等的id是接口中方法名称
5):dao接口中不要使用重载方法,不要使用同名的,不同参数的方法
参数:从Java代码中把实际的值传入到mapper中
1):一个简单类型的参数:#{任意字符}
2):多个简单类型的参数,使用@Param(自定义名称)
3):使用一个Java对象,对象的属性值作为mapper文件找到参数,#{java对象属性名称}
#和s的区别:
1.#是占位符,表示列值的,放在等号右侧
2.$占位符,表示字符串的连接,把sql语句将连接成一个字符串
3.#占位符使用的jdbc只当PreparedStatement对象执行SQL语句,效率高,没有sql注入的风险
4.s使用的Statement对象执行sql,效率低,有sql注入风险
多对一:
对于学生而言,多个学生关联一个老师(关联)
主要是mapper.xml配置文件中sql语句的查询
<select id="getStudent" resultMap="StudentTeacher">
<!--
思路:
1.查询所有的学生信息
2.根据查询出来的学生的tid,查找对应的老师
-->
SELECT s.`id` sid , s.`name` sname , t.`name` tname
FROM student s,teacher t
WHERE s.`tid` = t.`id`;
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<!--复杂处理 assocaiation:对象-->
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
一对多:
对于老师而言,一个老师有很多学生(集合)
<select id="getTeacher" resultMap="TeacherStudent">
SELECT t.`id` tid , t.`name` tname , s.`id` sid , s.`name` sname
FROM teacher t,student s
WHERE t.`id` = s.`tid` and t.`id` = #{tid};
</select>
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!--复杂的属性 collection:集合-->
<collection property="student" ofType="student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
小结一下:
1.关联 - association 【多对一】
2.集合 - collection 【一对多】
3.javaType & ofType
1.JavaType用来指定实体类中属性的类型
2. ofType 用来指定映射到List或者集合中的pojo类型,泛型中的约束类型!
面试高频:
Mysql引擎
lnnoDB底层原理
索引
索引优化!
动态SQL
缓存:
查询:连接数据库,耗资源!
一次查询的结果,给他暂存在一个可以直接取到的地方!–>内存:缓存
我们再次查询相同数据的时候,直接走缓存,就不用走数据库了
1.什么是缓存[ Cache ]
1.1 存在内存中的临时数据。
1.2 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。
2.为什么使用缓存?
减少和数据库的交互次数,减少系统开销,提高系统效率。
3.什么样的数据能使用缓存?
经常查询并且不经常改变的数据。
Mybatis缓存
1、MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。
2、MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
2.1 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)。
2.2 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
2.3 为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Lache接口来自定义二级缓存
一级缓存
一级缓存也叫本地缓存:
1.与数据库同一次会话期间查询到的数据会放在本地缓存中。
2.以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库
缓存失效的情况:
1.查询不同的东西
2.增删改操作,可能会改原来的数据,所以必定会刷新缓存
3.查询不同的Mapper.xml
4.手动清理缓存
小结:一级缓存是默认开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段
二级缓存
mybatis-config.xml配置:
<settings>
<!--显示的开启全局缓存-->
<setting name="cacheEnabled" value="true"/>
</settings>
Mapper.xml配置
<!--在当前 Mapper.xml文件开启二级缓存-->
<cache/>
也可以自定义cache标签参数
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
注意:我们需要将实体类序列化!否则会报错
public class User implements Serializable {
小结:
1.只要开启了二级缓存,在同一个Mapper下就有效所有的数据都2.会先放在一级缓存中;
3.只有当会话提交,或者关闭的时候,才会提交到二级缓冲中!
原理图:
SSM整合环境搭建
四、Linux操作系统
首先创建一个MAVEN空白工程,然后右键添加Web框架
然后创建相应的包
接下开始配置xml文件,先从myabtis开始
添加依赖
<?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>org.example</groupId>
<artifactId>ssm3</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
<!-- druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
<!--servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--Servlet - JSP -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!--事务相关-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!--jackson-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
</dependency>
</dependencies>
<build>
<!--将src下以及resources目录下的properties、xml文件编译后写出到target目录-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--settings:控制mybatis全局行为-->
<settings>
<!--设置mybatis输出日志-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--配置源交给spring-->
<!--别名设置-->
<typeAliases>
<package name="com.dong.pojo"/>
</typeAliases>
<mappers>
<mapper class="com.dong.dao.UserMapper"/>
</mappers>
</configuration>
jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/springmybatis
username=root
pwd=123
spring-dao.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
https://www.springframework.org/schema/context/spring-context.xsd">
<!--spirng配置文件:声明service dao 工具类等对象-->
<context:property-placeholder location="classpath:conf/jdbc.properties"/>
<!--声明数据源,连接数据库-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${pwd}"/>
<!--初始化值-->
<property name="initialSize" value="3" />
<!--最小空余的数量-->
<property name="minIdle" value="3" />
<!--最大连接数量-->
<property name="maxActive" value="20" />
<!--最长等待时间-->
<property name="maxWait" value="60000" />
<!--过滤器-->
<property name="filters" value="stat,wall" />
</bean>
<!--SqlSessionFactoryBean创建SqlSessionFacetory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:conf/mybatis-config.xml"/>
</bean>
<!--配置dao接口扫描包-->
<!-- spring与mybatis整合配置,自动扫描所有dao ,将dao接口生成代理注入到Spring-->
<!-- MapperScannerConfigurer 的作用是取代手动添加 Mapper ,自动扫描完成接口代理。
而不需要再在mybatis-config.xml里面去逐一配置mappers。 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--要扫描的dao包-->
<property name="basePackage" value="com.dong.dao"/>
</bean>
</beans>
spring-service.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" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--扫描service下的包-->
<context:component-scan base-package="com.dong.service"/>
<!--事务管理-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
springmvc.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:mvc="http://www.springframework.org/schema/mvc"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--注解驱动-->
<mvc:annotation-driven/>
<!--静态资源过滤-->
<mvc:default-servlet-handler/>
<!--扫描包-->
<context:component-scan base-package="com.dong.controller"/>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
全部配置好后交给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">
<import resource="classpath:conf/spring-dao.xml"/>
<import resource="classpath:conf/spring-service.xml"/>
<import resource="classpath:conf/springmvc.xml"/>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
version="4.0">
<!--注册中央调度器DispatcherServlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:conf/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--注册spring的监听器-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:conf/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextCleanupListener</listener-class>
</listener>
<!--注册字符集过滤器-->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
配置完后,自己手动配置一下tomcat即可编写测试代码运行以便测试环境
学习内容来自B站尚硅谷教学、狂神说、动力节点等视频 再加上自己的部分理解