Spring笔记

Spring笔记

1、简介

spring理念:是现有的技术更加容易使用,本身是一个大杂烩。

  • SSH:Struct2 + Spring + Hibernate
  • SSM: SpringMVC + Spring + Mybatis

官网: https://spring.io/projects/spring-framework#overview

官方下载: https://repo.spring.io/release/org/springframework/spring/

GitHub: https://github.com/spring-projects/spring-framework

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <!--spring的集合包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.16</version>
        </dependency>
        <!--spring操作数据库的话,需要spring-jdbc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.16</version>
        </dependency>
  • spring是开源的免费的容器
  • spring是一个轻量级的,非入侵式的。
  • 控制反转(IOC),面向切面编程 (AOP)。
  • 支持事务处理,对框架整合的支持。
  • 总结:spring是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架。

2、IOC理论

  1. UserDao

  2. UserDaoImp

  3. UserSevice

  4. UserServiceImp

在之前,用户的需求可能会影响原来的代码。

使用一个set。

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

之前是主动创建对象,控制权在程序员手上。

使用set之后,是被动接受对象。

3、 Hello Spring

pojo中

public class Hello {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Hello{" +
                "name='" + name + '\'' +
                '}';
    }
}

resource中

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="hello" class="com.sun.pojo.Hello">
        <property name="str" value="spring"/>
    </bean>

</beans>

test

public class Mytest {
    public static void main(String[] args) {
        //获取ApplicationContext:得到spring容器
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //得到容器后,从容其中获取对象:Bean
        Hello hello = (Hello) context.getBean("hello");
        System.out.println(hello.toString());
    }
}

bean = 对象
id = 变量名
class = new的对象
property 相当于给对象中的属性设值

核心用set注入

第一个文件中

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--使用Spring来创建对象,在Spring中的这些叫做Bean
        类型 变量名 = new 类型();
        Hello hello = new Hello();

        id = 变量名
        class = new 的对象
        property 相当于给对象中给的属性赋值
    -->

    <bean id="userDaoImpl" class="com.sun.dao.UserDaoImpl"/>
    <bean id="mysqlImpl" class="com.sun.dao.UserDaoMysqlImpl"/>
    <bean id="oracleImpl" class="com.sun.dao.UserDaoOracleImpl"/>

    <bean id="userServiceImpl" class="com.sun.service.UserServiceImpl">
        <!--
            name:UserServiceImpl中的属性
            ref:引用spring容器中创建好的对象
            value:具体的值,基本数据类型
        -->
        <property name="userDao" ref="oracleImpl"/>
    </bean>
</beans>

4、IOC创建对象的方式

  1. 使用无参构造创建对象,默认。
  2. 使用有参构造
  • 下标赋值
<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="user" class="com.hou.pojo.User">
        <constructor-arg index="0" value="hou"/>
    </bean>
</beans>
  • 类型赋值(不建议使用)
<bean id="user" class="com.sun.pojo.User">
    <constructor-arg type="java.lang.String" value="sun"/>
</bean>
  • 直接通过参数名
<bean id="user" class="com.sun.pojo.User">
    <constructor-arg name="name" value="sun"></constructor-arg>
</bean>

5、 Spring配置

别名

<bean id="user" class="com.sun.pojo.User">
    <constructor-arg name="name" value="sun"></constructor-arg>
</bean>
<alias name="user" alias="user2"/>

Bean的配置

  • id:bean的id标识符
  • class:bean对象所对应的类型
  • name:别名,更高级,可以同时取多个别名。

import

一般用于团队开发,它可以将多个配置文件,导入合并为一个

<import resource="beans.xml"/>

6、 DI依赖注入

构造器注入

set方式注入(重点)

  • 依赖:bean对象的创建依赖于容器
  • 注入:bean对象中的所有属性,由容器来注入

【环境搭建】

  1. 复杂类型
  2. 真实测试对象
  • Student实体类
public class Student {

    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbies;
    private Set<String> games;
    private Map<String,String> card;
    private String wife;
    private Properties info;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public String[] getBooks() {
        return books;
    }

    public void setBooks(String[] books) {
        this.books = books;
    }

    public List<String> getHobbies() {
        return hobbies;
    }

    public void setHobbies(List<String> hobbies) {
        this.hobbies = hobbies;
    }

    public Set<String> getGames() {
        return games;
    }

    public void setGames(Set<String> games) {
        this.games = games;
    }

    public Map<String, String> getCard() {
        return card;
    }

    public void setCard(Map<String, String> card) {
        this.card = card;
    }

    public String getWife() {
        return wife;
    }

    public void setWife(String wife) {
        this.wife = wife;
    }

    public Properties getInfo() {
        return info;
    }

    public void setInfo(Properties info) {
        this.info = info;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", address=" + address +
                ", books=" + Arrays.toString(books) +
                ", hobbies=" + hobbies +
                ", games=" + games +
                ", card=" + card +
                ", wife='" + wife + '\'' +
                ", info=" + info +
                '}';
    }
}

  • Address实体类
public class Address {
    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}
  • 配置文件
<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--开启注解的支持-->
    <context:annotation-config/>
    <!--指定要扫描的包,这个包下而的注解就会生效-->
    <context:component-scan base-package="com.sun.pojo"/>
  
    <bean id="address" class="com.sun.pojo.Address">
        <property name="address" value="Nuist"></property>
    </bean>

    <bean id="student" class="com.sun.pojo.Student">
        <property name="name" value="sun"/>
        <property name="address" ref="address"/>

        <!--数组注入-->
        <property name="books">
            <array>
                <value>三国</value>
                <value>西游</value>
                <value>水浒</value>
            </array>
        </property>

        <!--list-->
        <property name="hobbies">
            <list>
                <value>eat</value>
                <value>drink</value>
                <value>play</value>
            </list>
        </property>

        <property name="card">
            <map>
                <entry key="1" value="12"/>
                <entry key="2" value="23"/>
            </map>
        </property>

        <property name="game">
            <set>
                <value>coc</value>
                <value>bob</value>
                <value>lol</value>
            </set>
        </property>

        <property name="wife">
            <null></null>
        </property>

        <!--properties-->
        <property name="infor">
            <props>
                <prop key="id">123456</prop>
                <prop key="name">wsx</prop>
            </props>
        </property>
    </bean>

</beans>

第三方

p标签和c标签

public class User {

    private String name;
    private int age;

    public User() {
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
<?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">

    <!--p命名空间注入/set注入-->
    <bean id="user" class="com.sun.pojo.User" p:name="sun" p:age="25"/>
    <!--传统的bean-->
	  <bean name="user" class="com.sun.pojo.User">
	        <property name="name" value="sun"/>
	        <property name="age" value="25"/>
	  </bean>
	<!--p:name与p:age则是p命名的作用 可以直接在标签上赋值,相当于替代了property-->

    <!--c命名空间/构造器-->
    <bean id="user2" class="com.sun.pojo.User" c:name="sun" c:age="25"/>
	<!--传统bean-->
	<bean name="user2" class="com.sun.pojo.User">
	        <constructor-arg name="name" value="sun"/>
	        <constructor-arg name="age" value="25"/>
	</bean>
	<!--c:name与c:age则是c命名的作用 可以直接在标签上赋值,相当于替代了constructor-arg-->
</beans>

bean的作用域

1586093707060

  1. 单例模式(默认)
<bean id="user2" class="com.sun.pojo.User" c:name="sun" c:age="25" scope="singleton"></bean>
  1. 原型模式: 每次从容器中get的时候,都产生一个新对象!
<bean id="user2" class="com.sun.pojo.User" c:name="sun" c:age="25" scope="prototype"></bean>
  1. 其余的requestsessionapplication这些只能在web开放中使用!

7、 Bean的自动装配

  • 自动装配是Spring是满足bean依赖的一种方式
  • Spring会在上下文自动寻找,并自动给bean装配属性

在Spring中有三种装配的方式

  1. 在xml中显示配置

  2. 在java中显示配置

  3. 隐式的自动装配bean 【重要】

  4. 环境搭建:一个人有两个宠物

  5. Byname自动装配:byname会自动查找,和自己对象set对应的值对应的id

保证所有id唯一,并且和set注入的值一致

  1. Bytype自动装配:byType会自动查找,和自己对象属性相同的bean

保证所有的class唯一

public class Cat {
    public void jiao(){
        System.out.println("miao");
    }
}
public class Dog {
    public void jiao(){
        System.out.println("wang~");
    }
}
public class Person {
    @Value("sun")
    private String name;
    //如果显示定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
    @Autowired(required = false)
    //使用Qualifier(value = "cat1")去配置@Autowired的使用,指定一个唯一的bean对象注入
    @Qualifier(value = "cat1")
    private Cat cat;
    @Resource
    @Autowired
    private Dog dog;


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = 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;
    }

}
<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">


    <bean id="cat1" class="com.sun.pojo.Cat"/>
    <bean id="cat248" class="com.sun.pojo.Cat"/>
    <bean id="dog" class="com.sun.pojo.Dog"/>
    <bean id="dog2" class="com.sun.pojo.Dog"/>

    <!--byName;名字和类型一致-->
    <!--byType:类型在Bean中唯一-->
    <bean id="person" class="com.sun.pojo.Person" autowire="byName">
        <property name="name" value="孙逊"/>
    </bean>
</beans>

使用注解自动装配

jdk1.5支持的注解,spring2.5支持的注解

The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML.

导入context约束

<?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
        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/>

</beans>

@Autowire

在属性上个使用,也可以在set上使用,可以不用编写set方法了

public class People {
    @Autowired
    private Cat cat;
    @Autowired
    private Dog dog;
    private String name;
}
@Nullable 字段标志的注解,说明这个字段可以为null

如果@Autowired自动装配环境比较复杂。自动装配无法通过一个注解完成的时候,可以使用@Qualifier(value = "dog")去配合使用,指定一个唯一的id对象

public class People {
    @Autowired
    private Cat cat;
    @Autowired
    @Qualifier(value = "dog")
    private Dog dog;
    private String name;
}

@Resource(name="dog")也可以

区别:

  • @autowire通过byType实现,而且必须要求这个对象存在

  • @resource默认通过byName实现,如果找不到,通过byType实现

8、 使用注解开发

在spring4之后,必须要保证aop的包导入

使用注解需要导入contex的约束

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/beans/spring-context.xsd">

    <!--开启注解支持-->
    <context:annotation-config/>
    <!--指定要扫描的包,这个包下而的注解就会生效-->
    <context:component-scan base-package="com.sun"/>

</beans>
  1. 属性如何注入

@Component//等价于<bean id="user" class="com.sun.pojo.User"/>
@Scope("singleton")//作用域
public class User {
    @Value(value = "sun")//等价于<property name="name" value="sun"/>
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

  1. 衍生的注解

@Component有几个衍生注解,会按照web开发中,mvc架构中分层。

  • dao (@Repository)
@Repository
public class UserDao {
}
  • service(@Service)
@Service
public class UserService {
}
  • controller(@Controller)
@Controller
public class UserController {
}

这四个注解功能一样的,都是代表将某个类注册到容器中

  1. 作用域
@Component//等价于<bean id="user" class="com.sun.pojo.User"/>
@Scope("singleton")//作用域
public class User {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

小结:

xml与注解

  • xml更加万能,维护简单
  • 注解,不是自己的类,使用不了,维护复杂

最佳实践:

  • 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"
       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/beans/spring-context.xsd">

    <!--开启注解支持-->
    <context:annotation-config/>
    <!--指定要扫描的包,这个包下而的注解就会生效-->
    <context:component-scan base-package="com.sun"/>

</beans>

9、 使用java方式配置spring

JavaConfig

Spring的一个子项目,在spring4之后,,他成为了核心功能

//这个也会被spring托管,注册到容器中,因为它本质就是一个@Component
//代表这是一个配置类,相当于之前的applicationContext.xml
@Configuration
@ComponentScan("com.sun")//因为本身相当于配置文件,所以配置文件中的扫描包也可以使用
@Import(Myconfig2.class)//同样可以一个配置文件引用另一个配置文件
public class Myconfig {

    //注册一个bean,就相当于我们之前的bean标签
    //这个方法的名字,就相当于bean标签中的id
    //这个方法的返回值,就相当于bean标签中的class
    @Bean
    public User getUser(){
        return new User();//就是返回要注入到bean的对象
    }
}
@Component
public class User {

    @Value("sun")
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}

这种纯java配置方式在springboot中随处可见

10、 动态代理

动态代理和静态代理

角色一样

动态代理类是动态生成的,不是我们直接写好的!

动态代理:基于接口,基于类

  • 基于接口:JDK的动态代理【使用】
  • 基于类:cglib
  • java字节码

InvocationHandler
Proxy

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

//动态代理不需要自己写代理类,而是通过Proxy代理类 和InvocationHandler调用处理程序类自动生成代理类并执行代理类
public class ProxyInvocationHandler implements InvocationHandler {

    //被代理的实例
    private Object object;

    public void setTarget(Object object) {
        this.object = object;
    }

    //生成代理类
    public Object getProxy(){
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),
                object.getClass().getInterfaces(), this);//中间参数是被代理的实例的接口
    }

    //处理代理实例,并返回结果
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        //如何判断执行的是哪个公共业务?
        log(method.getName());
        //动态代理的本质,就是使用反射机制
        return method.invoke(object, args);
    }

    //公共事务:日志方法
    public void log(String msg){
        System.out.println("执行了"+msg+"方法");
    }

}
//抽象角色:租房
public interface Rent {

    public void rent();
}
//真实角色:需要被代理的角色:房东
public class Landlord  implements Rent{

    @Override
    public void rent() {
        System.out.println("房东要出租房子");
    }
}
import org.junit.Test;

//客户端访问代理角色/真实角色
public class Client {
    @Test
    public void test(){
        //房东直接租房子
        Landlord landlord = new Landlord();
        landlord.rent();
    }

    @Test
    public void test2(){

        //房东要租房子
        Landlord landlord = new Landlord();
        //代理,中介帮房东租房子,代理角色一般都会有一些附属操作,比如中间赚取中介费
        Proxy proxy = new Proxy(landlord);//构造函数的方式还是需要new一个新对象
        //客户不用面对房东,直接找代理租房即可
        proxy.rent();
    }
}

11、AOP

<dependencies>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.4</version>
    </dependency>
</dependencies>

方法一:使用spring接口【springAPI接口实现】

<?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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beanss
        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-->
    <bean id="userservice" class="com.service.UserServiceImp"></bean>
    <bean id="log" class="com.log.Log"/>
    <bean id="afterlog" class="com.log.AfterLog"/>

    <!--方式一:使用Spring API接口-->
    <!--配置AOP:需要导入aop的约束-->
    <aop:config>
        <!--切入点:expression:表达式,execution(要执行的位置)-->
        <aop:pointcut id="point" expression="execution(* com.service.UserServiceImp.*(..))"/>
        <!--执行环绕增加!:不同的类在切入点前后-->
        <aop:advisor advice-ref="log" pointcut-ref="point"/>
        <aop:advisor advice-ref="afterlog" pointcut-ref="point"/>
    </aop:config>

</beans>
public class UserServiceImp implements UserService {


    public void add() {
        System.out.println("add");
    }

    public void delete() {
        System.out.println("delete");
    }

    public void query() {
        System.out.println("query");
    }

    public void update() {
        System.out.println("update");
    }
}
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());
    }
}
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);
    }
}
pu
public class Mytest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("ApplcationContext.xml");
        //动态代理代理的是接口
        UserService userService = (UserService) context.getBean("userservice");
        userService.add();
    }
}

方法二:自定义类来实现AOP【主要是切面定义】

  1. 自定义一个类
public class DiyPointcut {

    public void before(){
        System.out.println("before");
    }

    public void after(){
        System.out.println("after");
    }
}
  1. 配置aop
<?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: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-->
    <bean id="userservice" class="com.service.UserServiceImp"></bean>
    <bean id="log" class="com.log.Log"/>
    <bean id="afterlog" class="com.log.AfterLog"/>

    <bean id="diy" class="com.diy.DiyPointcut">
    </bean>
    <aop:config>
        <!--自定义切面,ref要引用一个类-->
        <aop:aspect ref="diy">
            <!--切入点-->
            <aop:pointcut id="point" expression="execution(* com.service.UserServiceImp.*(..))"/>
            <!--通知:同一类(自定义切面)中的不同方法在切入点前后-->
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>

</beans>

方法三:注解方式

<?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: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">
    
    < <!--方式三:注解注释-->
    <context:annotation-config/>
    <context:component-scan base-package="com.sun"/>
    <bean id="annotationpoingcut" class="com.sun.diy.AnnotationPointCut"/>
    <!--开启支持注解 基于接口JDK(默认):proxy-target-class="false"  基于类cglib:proxy-target-class="true"-->
    <aop:aspectj-autoproxy/>
    <!--注册bean-->
    <bean id="userservice" class="com.service.UserServiceImp"></bean>
    
</beans>
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;
import org.springframework.context.annotation.Configuration;

@Configuration//代替配置文件中的<bean>,需要开启注解支持
@Aspect//标注这个类是一个切面,需要开启切面自动代理注解支持
public class AnnotationPointCut {

    @Before("execution(* com.sun.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("===========方法执行前===========");
    }
    @After("execution(* com.sun.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("==========方法执行后============");
    }

    //在环绕增强中,可以给定一个参数,代表要获取处理的切入点
    @Around("execution(* com.sun.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("环绕前");
        Signature signature = joinPoint.getSignature();//获得签名
        System.out.println("signature"+signature);
        //执行方法
        Object proceed = joinPoint.proceed();

        System.out.println("环绕后");
        System.out.println(proceed);
    }
}

12、 整合mybatis

文档: https://mybatis.org/spring/zh/

回顾mybatis

  1. 注入依赖
<?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">
    <parent>
        <artifactId>spring-study</artifactId>
        <groupId>com.hou</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>spring-10-mybatis</artifactId>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.4</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>


        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

</project>
  1. 配置文件
<?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>

    <typeAliases>
        <package name="com.pojo"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://111.230.212.103:3306/mybatis?userSSL=true&amp;
                userUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="hdk123"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper class="com.mapper.UserMapper"/>
    </mappers>
</configuration>
  1. 接口
public interface UserMapper {
   List<User> selectUser();
}
  1. mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.mapper.UserMapper">

    <select id="selectUser" resultType="user">
        select * from mybatis.user;
    </select>

</mapper>

整合mybatis-spring

方法一:使用SqlSessionTemplate代替SqlSession

-配置spring.xml文件

  1. 编写数据源配置
  2. SqlSessionFactory
  3. SqlSessionTemplate
  4. 需要给接口加入实现类
  5. 测试
  • mybatis.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>

    <typeAliases>
        <package name="com.pojo"/>
    </typeAliases>

</configuration>
  • 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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--DataSource:使用Spring的数据源代替Mybatis的数据源
    Spring提供的JDBC:org.springframework.jdbc.datasource.DriverManagerDataSource
    -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=UTF-8&amp;useSSL=true"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>


    <!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource" />
        <!--注入mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--注入mapper-->
        <property name="mapperLocations" value="classpath:com/sun/mapper/*.xml"/>
    </bean>

    <!--SqlSessionTemplate:就是之前使用的sqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory" />
    </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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="spring-dao.xml"/>

    <bean id="userMapper" class="com.sun.mapper.UseMapperImpl">
        <property name="sqlSessionTemplate" ref="sqlSession"/>
    </bean>
</beans>

UserMapperImpl

public class UseMapperImpl implements UserMapper{

    //原来使用SqlSession执行,现在使用SqlSessionTemplate

    private SqlSessionTemplate sqlSessionTemplate;

    //属性需要在bean中注入,需要set方法
    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
        this.sqlSessionTemplate = sqlSessionTemplate;
    }

    @Override
    public List<User> getUserList() {
        UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
        return mapper.getUserList();
    }
}
  • test
public class Mytest {

    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper2", UserMapper.class);
        for (User user : userMapper.getUserList()) {
            System.out.println(user);
        }

    }

}

方法二:SqlSessionDaoSupport:直接获取getSqlSession()

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--data source-->
    <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://111.230.212.103:3306/mybatis?userSSL=true&amp;
                userUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="hdk123"/>
    </bean>

    <!--sqlsession-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="datasource" />
        <!--bound mybatis-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/mapper/UserMapper.xml"/>
    </bean>

    <bean id="userMapper2" class="com.mapper.UserMapperIml2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>

</beans>
public class UserMapperIml2 extends SqlSessionDaoSupport implements UserMapper {
    public List<User> selectUser() {
        SqlSession sqlSession = getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUser();
    }
}

13、 声明式事务

要么都成功,要么都失败
十分重要,涉及到数据一致性
确保完整性和一致性
事务的acid原则:

  • 原子性
  • 一致性
  • 隔离性:多个业务可能操作一个资源,防止数据损坏
  • 持久性:事务一旦提交,无论系统发生什么问题,结果都不会被影响。

Spring中的事务管理

  • 声明式事务
  • 编程式事务

在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:tx="http://www.springframework.org/schema/tx"
       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/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--DataSource:使用Spring的数据源代替Mybatis的数据源
    Spring提供的JDBC:org.springframework.jdbc.datasource.DriverManagerDataSource
    -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=UTF-8&amp;useSSL=true"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>


    <!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource" />
        <!--注入mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--注入mapper-->
        <property name="mapperLocations" value="classpath:com/sun/mapper/*.xml"/>
    </bean>

    <!--SqlSessionTemplate:就是之前使用的sqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory" />
    </bean>

    <!--配置声明式事务:事务的ACID原则:原子性、一致性、隔离性、持久性,不配置无法保证这些原则-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <constructor-arg ref="dataSource" />
    </bean>

    <!--结合AOP实现事务的织入-->
    <!--配置事务-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--给哪些方法配置事务-->
        <!--配置事务的传播特性:propagation= 共7中传播特性,默认REQUIRED-->
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="query" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!--配置事务切入-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.sun.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>

</beans>

在applicationContext.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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="spring-dao.xml"/>

    <bean id="userMapper" class="com.sun.mapper.UseMapperImpl">
        <property name="sqlSessionTemplate" ref="sqlSession"/>
    </bean>

</beans>
  • 接口
public interface UserMapper {
    List<User> getUserList();

    //增加一个用户
    int addUser(User user);

    //删除一个用户
    int deleteUser(@Param("id")int id);

}

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.sun.mapper.UserMapper">

    <!--select查询语句-->
    <select id="getUserList" resultType="com.sun.pojo.User">
        select * from mybatis.user
    </select>

    <insert id="addUser" parameterType="user">
        insert into mybatis.user (id,username,userpwd)
        values (#{id},#{username},#{userpwd});
    </insert>

    <!--故意写错,验证事务的ACID原则:原子性、一致性、隔离性、持久性-->
    <delete id="deleteUser" parameterType="int">
        deletes from mybatis.user where id=#{id}
    </delete>

</mapper>

public class UseMapperImpl extends SqlSessionDaoSupport implements UserMapper{

    @Override
    public List<User> getUserList() {
        User user = new User(10, "王浩", "12435855");
        addUser(user);
        deleteUser(10);
        return getSqlSession().getMapper(UserMapper.class).getUserList();
    }

    @Override
    public int addUser(User user) {
        return getSqlSession().getMapper(UserMapper.class).addUser(user);
    }

    @Override
    public int deleteUser(int id) {
        return getSqlSession().getMapper(UserMapper.class).deleteUser(id);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值