视频连接:https://www.bilibili.com/video/BV1WE411d7Dv?p=1
Spring ——> 春天,为开源软件带来了春天
2002,首次推出了Spring框架的雏形:interface21框架!
Spring框架以interface21框架为基础,经过重新设计,并不断丰富其内涵,于2004年3月24日发布了1.0正式版
Spring的理念:使用现有的技术更加容易使用,本身是一个大杂烩,整合了现有的技术框架!
SSH:Struct2 + Spring + Hibernate(全自动持久化框架)!
SSM:SpringMVC + Spring + MyBatis(半自动持久化框架,可自定义性质更强)!
spring官网: https://spring.io/projects/spring-framework#overview
官方下载: https://repo.spring.io/release/org/springframework/spring/
GitHub: https://github.com/spring-projects/spring-framework
Spring Web MVC: spring-webmvc最新版
Spring Web MVC和Spring-JDBC的pom配置文件:
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.2.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.2.7.RELEASEversion>
dependency>
=== 总结一句话:Spring就是一个轻量级的控制反转(IoC)和面向切面编程(AOP)的框架! ===
现代化的java开发 -> 基于Spring的开发!
因为现在大多数公司都在使用SpringBoot进行快速开发,学习SpringBoot的前提,需要完全掌握Spring及SpringMVC!承上启下的作用!
传统的调用
UserDao
package dao;
public interface UserDao {
void getUser();
}
UserDaoImp
package dao;
public class UserDaoImpl implements UserDao{
public void getUser() {
System.out.println("默认获取用户数据");
}
}
UserSevice
package Service;
public interface UserService {
void getUser();
}
UserServiceImp
package Service;
import dao.UserDao;
import dao.UserDaoImpl;
public class UserServiceImpl implements UserService{
UserDao userDao = new UserDaoImpl();
public void getUser(){
userDao.getUser();
}
}
测试
package holle0;
import Service.UserService;
import Service.UserServiceImpl;
public class MyTest0 {
public static void main(String[] args) {
// 用户实际调用的是业务层,dao层他们不需要接触
UserService userService = new UserServiceImpl();
userService.getUser();
}
}
在我们之前的业务中,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改原代码!如果程序代码量十分大,修改一次的成本代价十分昂贵!
**改良:**我们使用一个Set接口实现。已经发生了革命性的变化!
//在Service层的实现类(UserServiceImpl)增加一个Set()方法
//利用set动态实现值的注入!
//DAO层并不写死固定调用哪一个UserDao的实现类
//而是通过Service层调用方法设置实现类!
private UserDao userDao;
public void setUserDao(UserDao userDao){
this.userDao = userDao;
}
set() 方法实际上是动态改变了 UserDao userDao 的 初始化部分(new UserDaoImpl())
测试中加上
((UserServiceImpl)userService).setUserDao(new UserDaoImpl());
本质上解决了问题,程序员不用再去管理对象的创建
系统的耦合性大大降低,可以更专注在业务的实现上
这是IoC(控制反转)的原型,反转(理解):主动权交给了用户
在父模块中导入jar包
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.2.7.RELEASEversion>
dependency>
pojo的Hello.java
package pojo;
public class Hello {
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return "Holle [str=" + str + "]";
}
}
在resource里面的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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hello" class="pojo.Hello">
<property name="str" value="Spring"/>
bean>
beans>
测试类MyTest
package holle1;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pojo.Hello;
public class MyTest {
public static void main(String[] args) {
//获取Spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//我们的对象下能在都在spring·中管理了,我们要使用,直接取出来就可以了
Hello holle = (Hello) context.getBean("hello");
System.out.println(holle.toString());
}
}
核心用set注入,所以必须要有下面的set()方法
//Hello类
public void setStr(String str) {
this.str = str;
}
思考:
IoC:对象由Spring 来创建,管理,装配!
在前面第一个module试试引入Spring
<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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userDaomSql" class="dao.UserDaoMysqlImpl">bean>
<bean id="userServiceImpl" class="service.UserServiceImp">
<property name="userDao" ref="userDaomSql"/>
bean>
beans>
第一个module改良后测试
package holle0;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.UserServiceImpl;
public class MyTest0 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("userServiceImpl");
userServiceImpl.getUser();
}
}
总结:
所有的类都要装配的beans.xml 里面;
所有的bean 都要通过容器去取;
容器里面取得的bean,拿出来就是一个对象,用对象调用方法即可;
下标赋值
index指的是有参构造中参数的下标,下标从0开始;
<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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user" class="pojo.User">
<constructor-arg index="0" value="chen"/>
bean>
beans>
类型赋值(不建议使用)
<bean id="user" class="pojo.User">
<constructor-arg type="java.lang.String" value="kuang"/>
bean>
直接通过参数名(掌握)
<bean id="user" class="pojo.User">
<constructor-arg name="name" value="kuang">constructor-arg>
bean>
注册bean之后对象就被初始化了(类似 new 类名())
name方式还需要无参构造和set方法,index和type只需要有参构造
就算是new 两个对象,也是只有一个实例(单例模式:全局唯一)
User user = (User) context.getBean("user");
User user2 = (User) context.getBean("user");
system.out.println(user == user2)//结果为true
总结:在配置文件加载的时候,容器(< bean>)中管理的对象就已经初始化了
<bean id="user" class="pojo.User">
<constructor-arg name="name" value="chen">constructor-arg>
bean>
<alias name="user" alias="userLove"/>
<bean id="user" class="pojo.User" name="u1 u2,u3;u4">
<property name="name" value="chen"/>
bean>
import一般用于团队开发使用,它可以将多个配置文件,导入合并为一个
假设,现在项目中有多个人开发,这三个人复制不同的类开发,不同的类需要注册在不同的bean中,我们可以利
用import将所有人的beans.xml合并为一个总的!
张三(beans.xm1)
李四(beans2.xm1)
王五(beans3.xm1)
applicationContext.xml
<import resource="beans.xm1"/>
<import resource="beans2.xml"/>
<import resource="beans3.xm1"/>
使用的时候,直接使用总的配置就可以了
按照在总的xml中的导入顺序来进行创建,后导入的会重写先导入的,最终实例化的对象会是后导入xml中的那个
第4点有提到
依赖注入:set注入!
【环境搭建】
复杂类型
Address类
真实测试对象
Student类
beans.xml
测试
MyTest3
Student类
package pojo;
import java.util.*;
@Get
@Set
public class Student {
//别忘了写get和set方法(用lombok注解也行)
private String name;
private Address address;
private String[] books;
private List<String> hobbies;
private Map<String, String> card;
private Set<String> game;
private Properties infor;
private String wife;
@Override
public String toString() {
return "Student{" +"\n"+
"name='" + name + '\'' +"\n"+
", address=" + address.toString() +"\n"+
", books=" + Arrays.toString(books) +"\n"+
", hobbies=" + hobbies +"\n"+
", card=" + card +"\n"+
", game=" + game +"\n"+
", infor=" + infor +"\n"+
", wife='" + wife + '\'' +"\n"+
'}';
}
}
Address类
package pojo;
public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Address{" +
"address='" + address + '\'' +
'}';
}
}
beans.xml
<beans xmlns="ht springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="address" class="pojo.Address">
<property name="address" value="address你好" />
bean>
<bean id="student" class="pojo.Student">
<property name="name" value="name你好" />
<property name="address" ref="address" />
<property name="books">
<array>
<value>三国value>
<value>西游value>
<value>水浒value>
array>
property>
<property name="hobbies">
<list>
<value>唱value>
<value>跳value>
<value>rapvalue>
<value>篮球value>
list>
property>
<property name="card">
<map>
<entry key="username" value="root" />
<entry key="password" value="root" />
map>
property>
<property name="game">
<set>
<value>wangzhevalue>
<value>lolvalue>
<value>galnamevalue>
set>
property>
<property name="wife">
<null>null>
property>
<property name="infor">
<props>
<prop key="id">20200802prop>
<prop key="name">cbhprop>
props>
property>
bean>
beans>
MyTest3
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pojo.Student;
public class MyTest3 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student stu = (Student) context.getBean("student");
System.out.println(stu.toString());
}
}
官方文档位置
pojo增加User类
package pojo;
public class User {
private String name;
private int id;
public User() {
}
public User(String name, int id) {
super();
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "User [name=" + name + ", id=" + id + "]";
}
}
xmlns:p=“http://www.springframework.org/schema/p”
xmlns:c=“http://www.springframework.org/schema/c”
?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:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user" class="pojo.User" p:name="张三" p:id="20" >
bean>
<bean id="user2" class="pojo.User" c:name="张三" c:id="22">bean>
beans>
测试
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User user = context.getBean("user",User.class);//确定class对象,就不用再强转了
System.out.println(user.toString());
单例模式(Spring默认机制)
<bean id="user2" class="pojo.User" c:name="cxk" c:age="19" scope="singleton">bean>
单例模式是把对象放在pool中,需要再取出来,使用的都是同一个对象实例
<bean id="user2" class="pojo.User" c:name="cxk" c:age="19" scope="prototype">bean>
在Spring中有三种装配的方式
在xml中显示配置
在java中显示配置
隐式的自动装配bean 【重要】
环境搭建:一个人有两个宠物
pojo的Cat类
public class Cat {
public void shut(){
System.out.println("miao");
}
}
pojo的Dog类
public class Dog {
public void shut(){
System.out.println("wow");
}
}
pojo的People类
package pojo;
public class People {
private Cat cat;
private Dog dog;
private String name;
public Cat getCat() {
return cat;
}
public void setCat(Cat cat) {
this.cat = cat;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "People{" +
"cat=" + cat +
", dog=" + dog +
", name='" + name + '\'' +
'}';
}
}package pojo;
public class People {
private Cat cat;
private Dog dog;
private String name;
public Cat getCat() {
return cat;
}
public void setCat(Cat cat) {
this.cat = cat;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "People{" +
"cat=" + cat +
", dog=" + dog +
", name='" + name + '\'' +
'}';
}
}
byType会自动查找,和自己对象set方法参数的类型相同的bean
保证所有的class唯一(类为全局唯一)
<bean id="cat" class="pojo.Cat">bean>
<bean id="dog" class="pojo.Dog">bean>
<bean id="people1" class="pojo.People" autowire="byType">
<property name="name" value="李四">property>
bean>
byName会自动查找,和自己对象set对应的值对应的id
保证所有id唯一,并且和set注入的值一致
<bean id="cat" class="pojo.Cat">bean>
<bean id="dog" class="pojo.Dog">bean>
<bean id="people" class="pojo.People" autowire="byName">
<property name="name" value="李四">property>
bean>
小结:
byName只能取到小写,大写取不到
jdk1.5支持的注解,spring2.5支持的注解
The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML.(翻译:基于注释的配置的引入提出了一个问题,即这种方法是否比XML“更好”)
xmlns:context="http://www.springframework.org/schema/context"
<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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config>context:annotation-config>
beans>
默认是byType方式,如果匹配不上,就会byName
在属性上个使用,也可以在set上使用
我们可以不用编写set方法了,前提是自动装配的属性在Spring容器里,且要符合ByName 自动装配
public class People {
@Autowired
private Cat cat;
@Autowired
private Dog dog;
private String name;
}
@Nullable 字段标记了这个注解,说明该字段可以为空
public name(@Nullable String name){
}
//源码
public @interface Autowired {
boolean required() default true;
}
如果定义了Autowire的require属性为false,说明这个对象可以为null,否则不允许为空(false表示找不到装配,不抛出异常)
@Autowired不能唯一装配时,需要@Autowired+@Qualifier
如果@Autowired自动装配环境比较复杂。自动装配无法通过一个注解完成的时候,可以使用@Qualifier(value = “dog”)去配合使用,指定一个唯一的id对象
public class People {
@Autowired
private Cat cat;
@Autowired
@Qualifier(value = "dog1")
private Dog dog;
private String name;
}
弹幕评论:
如果xml文件中同一个对象被多个bean使用,Autowired无法按类型找到,可以用@Qualifier指定id查找
默认是byName方式,如果匹配不上,就会byType
public class People {
Resource(name="cat")
private Cat cat;
Resource(name="dog")
private Dog dog;
private String name;
}
Autowired是byType,@Autowired+@Qualifier = byType || byName
Autowired是先byteType,如果唯一則注入,否则byName查找。resource是先byname,不符合再继续byType
@Resource和@Autowired的区别:
在spring4之后,使用注解开发,必须要保证aop包的导入
使用注解需要导入contex的约束
<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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config>context:annotation-config>
<context:component-scan base-package="pojo">context:component-scan>
beans>
有了< context:component-scan>,另一个< context:annotation-config/>标签可以移除掉,因为已经被包含进去了。
<context:component-scan base-package="com.kuang"/>
<context:annotation-config/>
//@Component 组件
//等价于
@Component
public class User {
public String name ="张三";
}
@Component
public class User {
//相当于
@value("zhangsan")
public String name;
//也可以放在set方法上面
//@value("zhangsan")
public void setName(String name) {
this.name = name;
}
}
@Component有几个衍生注解,会按照web开发中,mvc架构中分层。
这四个注解的功能是一样的,都是代表将某个类注册到容器中
@Autowired:默认是byType方式,如果匹配不上,就会byName
@Nullable:字段标记了这个注解,说明该字段可以为空
@Resource:默认是byName方式,如果匹配不上,就会byType
//原型模式prototype,单例模式singleton
//scope("prototype")相当于
@Component
@scope("prototype")
public class User {
//相当于
@value("zhangsan")
public String name;
//也可以放在set方法上面
@value("zhangsan")
public void setName(String name) {
this.name = name;
}
}
xml与注解:
xml与注解最佳实践:
不使用Spring的xml配置,完全交给java来做!
JavaConfig是Spring的一个子项目,在spring4之后,它成为了核心功能
实体类:pojo的User.java
package pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//这里这个注解的意思,就是说明这个类被Spring接管了,注册到了容器中
@Component //等价于
public class User {
private String name;
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
public String getName() {
return name;
}
@Value("张三")
public void setName(String name) {
this.name = name;
}
}
要么使用@Bean,要么使用@Component和ComponentScan,两种效果一样
配置文件:config中的kuang.java
@Import(KuangConfig2.class),用@import来包含KuangConfig2.java
//这个也会Spring容器托管,注册到容器中,因为他本米就是一个@Component
// @Configuration表这是一个配置类,就像我们之前看的beans.xml,类似于标签
@Configuration
@componentScan("com.Kuang.pojo") //开启扫描
//@Import(KuangConfig2.class)
public class KuangConfig {
//注册一个bean , 就相当于我们之前写的一个bean 标签
//这个方法的名字,就相当于bean 标签中的 id 属性 ->getUser
//这个方法的返同值,就相当于bean 标签中的class 属性 ->User
//@Bean
public User getUser(){
return new User(); //就是返回要注入到bean的对象!
}
}
弹幕评论:ComponentScan、@Component("pojo”) 这两个注解配合使用
测试类
public class MyTest {
public static void main(String[ ] args) {
//如果完全使用了配置类方式去做,我们就只能通过 Annotationconfig 上下文来获取容器,通过配置类的class对象加载!
ApplicationContext context = new AnnotationConfigApplicationContext(KuangConfig.Class); //class对象
User getUser =(User)context.getBean( "getUser"); //方法名getUser
System.out.Println(getUser.getName());
}
}
为什么学习代理模式?
代理模式是SpringAOP的底层
角色分析:
代理模式的好处:
可以使真实角色的操作更加纯粹 不用去关注一些公共的业务
公共业务也就交给代理角色!实现了业务的分工
缺点:真实角色就会产生一个代理角色 代码量会翻倍 开发效率会降低
代码步骤:
1、接口
package pojo;
public interface Host {
public void rent();
}
2、真实角色
package pojo;
public class HostMaster implements Host{
public void rent() {
System.out.println("房东要出租房子");
}
}
3、代理角色
package pojo;
public class Proxy {
public Host host;
public Proxy() {
}
public Proxy(Host host) {
super();
this.host = host;
}
public void rent() {
seeHouse();
host.rent();
fee();
sign();
}
//看房
public void seeHouse() {
System.out.println("看房子");
}
//收费
public void fee() {
System.out.println("收中介费");
}
//合同
public void sign() {
System.out.println("签合同");
}
}
4、客户端访问代理角色
package holle4_proxy;
import pojo.Host;
import pojo.HostMaster;
import pojo.Proxy;
public class My {
public static void main(String[] args) {
//房东要出租房子
Host host = new HostMaster();
//中介帮房东出租房子,但也收取一定费用(增加一些房东不做的操作)
Proxy proxy = new Proxy(host);
//看不到房东,但通过代理,还是租到了房子
proxy.rent();
}
}
房东要出租房子
中介带你看房
收中介费
AOP横向开发
动态代理和静态角色一样,动态代理底层是反射机制
动态代理类是动态生成的,不是我们直接写好的!
动态代理(两大类):基于接口,基于类
了解两个类
1、Proxy:代理
2、InvocationHandler:调用处理程序
实例:
接口 Rent.java
package demo02;
public interface Rent {
public void rent();
}
接口Rent实现类 Host.java
package demo02;
//房东
public class Host implements Rent {
public void rent(){
System.out.println("房东要出租房子");
}
}
代理角色的处理程序类 ProxyInvocationHandler.java
package pojo2;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
///用这个类,自动生成代理
public class ProxyInvocationHandler implements InvocationHandler {
// Foo f =(Foo) Proxy.NewProxyInstance(Foo. Class.GetClassLoader(),
// new Class>[] { Foo.Class },
// handler);
//被代理的接口
private Rent rent;;
public void setRent(Rent rent) {
this.rent = rent;
}
// 得到生成的代理类
public Object getProxy() {
// newProxyInstance() -> 生成代理对象,就不用再写具体的代理类了
// this.getClass().getClassLoader() -> 找到加载类的位置
// hostMaster.getClass().getInterfaces() -> 代理的具体接口
// this -> 代表了接口InvocationHandler的实现类ProxyInvocationHandler
return Proxy.newProxyInstance(this.getClass().getClassLoader(), rent.getClass().getInterfaces(), this);
// 处理代理实例并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
seeHouse();
// 动态代理的本质,就是使用反射机制实现的
// invoke()执行它真正要执行的方法
Object result = method.invoke(hostMaster, args);
fee();
return result;
}
public void seeHouse() {
System.out.println("看房子");
}
public void fee() {
System.out.println("收中介费");
}
}
用户类 Client.java
package demo02;
public class Client {
public static void main(String[] args) {
//真是角色
Host host = new Host();
//代理角色 :现在没有
ProxyInvocationHandler pih = new ProxyInvocationHandler();
//通过调用程序处理角色来处理我们要调用的接口对象
pih.setRent(host);
Rent proxy = (Rent) pih.getProxy();
proxy.rent();
}
}
编写万能代理类
///用这个类,自动生代理
public class ProxyInvocationHandler implements InvocationHandler {
// 被代理的接口
public Object target;
public void setTarget(Object target) {
this.target = target;
}
// 得到生成的代理类 -> 固定的代码
public Object getProxy() {
return Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
}
// 处理代理实例并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 动态代理的本质,就是使用反射机制实现的
// invoke()执行它真正要执行的方法
Object result = method.invoke(target, args);
return result;
}
}
“全称Aspect Oriented Programming,面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。”
提供声明式事务,允许用户自定义切面
SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:
即AOP在不改变原有代码的情况下,去增加新的功能。(代理)
导入jar包
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.9.4version>
dependency>
springAPI接口实现
applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="userservice" class="service.UserServiceImpl"/>
<bean id="log" class="log.Log"/>
<bean id="afterLog" class="log.AfterLog"/>
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* service.UserServiceImpl.*(..))"/>
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
aop:config>
beans>
execution(返回类型,类名,方法名(参数)) -> execution(* com.service.,(…))
UserService.java
package service;
public interface UserService {
public void add();
public void delete();
public void update();
public void select();
}
UserService 的实现类 UserServiceImp.java
package service;
public class UserServiceImpl implements UserService {
public void add() {
System.out.println("增强一个用户");
}
public void delete() {
System.out.println("删除一个用户");
}
public void update() {
System.out.println("更新一个用户");
}
public void select() {
System.out.println("查询一个用户");
}
}
前置Log.java
package log;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class Log implements MethodBeforeAdvice {
//method:要执行的目标对象的方法
//args:参数
//target:目标对象
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
}
}
后置AfterLog.java
package log;
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
public class AfterLog implements AfterReturningAdvice {
//returnVaule: 返回值
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行了"+method.getName()+"方法,返回值是"+returnValue);
}
}
测试类MyTest5
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.UserService;
import service.UserServiceImpl;
public class Mytest {
@Test //方式一
public void test01(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//动态代理代理的是接口
UserService userService = context.getBean("userService", UserService.class);
userService.delete();
}
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="userservice" class="service.UserServiceImpl"/>
<bean id="log" class="log.Log"/>
<bean id="afterLog" class="log.AfterLog"/>
<bean id="diy" class="diy.DiyPointcut"/>
<aop:config>
<aop:aspect ref="diy">
<aop:pointcut id="point" expression="execution(* service.UserServiceImpl.*(..))"/>
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
aop:aspect>
aop:config>
beans>
package diy;
public class DiyPointcut {
public void before(){
System.out.println("插入到前面");
}
public void after(){
System.out.println("插入到后面");
}
}
@Test //方式二
public void test02(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//动态代理代理的是接口
UserService userService = context.getBean("userService", UserService.class);
userService.delete();
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="userservice" class="service.UserServiceImpl"/>
<bean id="diyAnnotation" class="diy.DiyAnnotation">bean>
<aop:aspectj-autoproxy/>
beans>
Annotation.java
package diy;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
//方式三 使用注解方式 实现Aop
@Aspect //标注这个类是一个切面
public class AnnotationPoinCut {
@Before("execution(* service.UserServiceImpl.*(..))") //插入切入点
public void before(){
System.out.println("****方法执行前*****");
}
@After("execution(* service.UserServiceImpl.*(..))") //插入切入点
public void after(){
System.out.println("****方法执行后*****");
}
//around 在环绕增强中 我们可以给定一个参数 代表我们要获取处理切入的点
@Around("execution(* service.UserServiceImpl.*(..))") //插入切入点
public void around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("环绕前");
//获得签名
Signature signature = jp.getSignature();
System.out.println(signature);
//执行方法
Object proceed = jp.proceed();
System.out.println(proceed);
System.out.println("环绕后");
}
}
测试
@Test //方式三
public void test03(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//动态代理代理的是接口
UserService userService = context.getBean("userService", UserService.class);
userService.delete();
}
输出结果:
环绕前
void service.UserService.delete()
****方法执行前*****
删除一个用户
****方法执行后*****
null
环绕后
mybatis-spring官网:https://mybatis.org/spring/zh/
mybatis的配置流程:
先导入jar包
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.2.10.RELEASEversion>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.9.4version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.2.2.RELEASEversion>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.2version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>2.0.4version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.12version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.12version>
dependency>
dependencies>
<build>
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
resources>
build>
代码步骤:
pojo实体类 User
package pojo;
import lombok.Data;
@Data
public class User {
private int id;
private String name;
private String pwd;
}
mapper目录有 UserMapper、UserMapperImpl、UserMapper.xml
接口UserMapper
package mapper;
import pojo.User;
import java.util.List;
public interface UserMapper {
public List<User> selectUser();
}
UserMapperImpl
package mapper;
import org.mybatis.spring.SqlSessionTemplate;
import pojo.User;
import java.util.List;
//我们所有操作 原来都是用sqlSession来执行 现在都使用sqlsessionTemplate
public class UserMapperImpl implements UserMapper {
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
public List<User> selectUser() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.selectUser();
}
}
UserMapperImpl2
package mapper;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import pojo.User;
import java.util.List;
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
public List<User> selectUser() {
SqlSession sqlSession = getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.selectUser();
return users;
}
}
UserMapper.xml
<mapper namespace="mapper.UserMapper">
<select id="selectUser" resultType="user">
select *from mybatis.user
select>
mapper>
resource目录下的 mybatis-config.xml、spring-dao.xml、applicationContext.xml
mybatis-config.xml
<configuration>
<properties resource="db.properties">properties>
<typeAliases>
<package name="pojo">package>
typeAliases>
configuration>
spring-dao.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver">property>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?userSSL=false&useUnicode=true&characterEncoding=UTF-8">property>
<property name="username" value="root">property>
<property name="password" value="root">property>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource">property>
<property name="configLocation" value="classpath:mybatis-config.xml">property>
<property name="mapperLocations" value="classpath:mapper/*.xml">property>
bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg ref="sqlSessionFactory"/>
bean>
beans>
applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<import resource="spring-dao.xml">import>
<bean id="userMapper" class="mapper.UserMapperImpl">
<property name="sqlSession" ref="sqlSession">property>
bean>
<bean id="userMapper2" class="mapper.UserMapperImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFactory">property>
bean>
beans>
测试类
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import mapper.UserMapper;
import pojo.User;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = (UserMapper) context.getBean("userMapper");
for (User user : userMapper.getUser()) {
System.out.println(user);
}
}
}
UserServiceImpl2
package mapper;
import pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
//继承SqlSessionDaoSupport 类
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
public List<User> getUser() {
SqlSession sqlSession = getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.getUser();
//或者一句话:return getSqlSession().getMapper(UserMapper.class).getUser();
}
}
spring-dao.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai"/>
<property name="username" value="root" />
<property name="password" value="root" />
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource" />
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
bean>
beans>
applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<import resource="spring-dao.xml" />
<bean id="userMapper2" class="mapper.UserMapperImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFactory">property>
bean>
beans>
测试
public class MyTest6 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = (UserMapper) context.getBean("userMapper2");
for (User user : userMapper.getUser()) {
System.out.println(user);
}
}
}
事务的ACID原则:
1、原子性 :要么都成功,要么都失败!
2、一致性
3、隔离性 :多个业务操作同一个资源 防止数据损坏
4、持久性 : 事务一旦提交 无论系统发生什么问题 结果都不会发生改变 被持久化写入到存储器中
ACID参考文章:https://www.cnblogs.com/malaikuangren/archive/2012/04/06/2434760.html
Spring中的事务管理
声明式事务
先导入jar包
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.2.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.9.4version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.2.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.2version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>2.0.4version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.12version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.12version>
dependency>
dependencies>
<build>
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
resources>
build>
代码步骤:
pojo实体类 User
package pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
mapper目录下的 UserMapper、UserMapperImpl、UserMapper.xml
接口UserMapper
package mapper;
import pojo.User;
import java.util.List;
public interface UserMapper {
public List<User> selectUser();
//添加一个用户
int addUser(User user);
//删除一个用户
int deleteUser(int id);
}
UserMapperImpl
package mapper;
import pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper {
public List<User> getUser() {
User user = new User(5,"你好","ok");
insertUser(user);
delUser(5);
SqlSession sqlSession = getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.getUser();
//或者return getSqlSession().getMapper(UserMapper.class).getUser();
}
//插入
public int insertUser(User user) {
return getSqlSession().getMapper(UserMapper.class).insertUser(user);
}
//删除
public int delUser(int id) {
return getSqlSession().getMapper(UserMapper.class).delUser(id);
}
}
UserMapper.xml
<mapper namespace="mapper.UserMapper">
<select id="selectUser" resultType="user">
select *from mybatis.user
select>
<insert id="addUser" parameterType="user">
insert into mybatis.user(id,name,pwd) values (#{id},#{name},#{pwd})
insert>
<delete id="deleteUser" >
deletessss from mybatis.user where id = #{id}
delete>
mapper>
resource目录下的 mybatis-config.xml、spring-dao.xml、applicationContext.xml
mybatis-config.xml
<configuration>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING" />
settings>
<typeAliases>
<package name="pojo" />
typeAliases>
configuration>
spring-dao.xml(已导入约束)
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver">property>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?userSSL=false&useUnicode=true&characterEncoding=UTF-8">property>
<property name="username" value="root">property>
<property name="password" value="root">property>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource">property>
<property name="configLocation" value="classpath:mybatis-config.xml">property>
<property name="mapperLocations" value="classpath:mapper/*.xml">property>
bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg ref="sqlSessionFactory"/>
bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="datasource">property>
bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* mapper.*.*(..))">aop:pointcut>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut">aop:advisor>
aop:config>
beans>
applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<import resource="spring-dao.xml">import>
<bean id="userMapper" class="mapper.UserMapperImpl">
<property name="sqlSession" ref="sqlSession">property>
bean>
beans>
测试类
加入事务之前 插入数据 成功 删除数据失败 也能插入数据
加入事务配置之后 同时插入数据和删除数据 有一个出错就 都不执行
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import mapper.UserMapper;import pojo.User;
public class MyTest7 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = (UserMapper) context.getBean("userMapper");
for (User user : userMapper.getUser()) {
System.out.println(user);
}
}
}
思考:
为什么需要事务?