4_Spring

Spring的基本组成:

1、最完善的轻量级核心框架。

2、通用的事务管理抽象层。

3、JDBC抽象层。

4、集成了Toplink, Hibernate, JDO, and iBATIS SQL Maps。

5、AOP功能。

6、灵活的MVC Web应用框架。

  • 直接在pom.xml中配置sping-webmvc依赖, 会自动导入其他依赖, 很方便

<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-webmvcartifactId>
    <version>5.3.5version>
dependency>
<dependency>
    <groupId>junitgroupId>
    <artifactId>junitartifactId>
    <version>4.12version>
    <scope>testscope>
dependency>
  • Spring是一个开源的免费的框架(容器)!

  • 轻量级的, 非入侵式的框架!

  • 控制反转 (IOC), 面向切面编程 (AOP)!

  • 支持事务的处理, 对框架整合的支持!

总结: Spring是一个轻量级的控制反转(IOC)和面向切面(AOP)的容器框架!

public class UserServiceImpl implements UserService {
    private UserDao userDao;

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

    public void getUser() {
        userDao.getUser();
    }
}
  • 之前, 程序是主动创建对象, 控制权在程序员手上
  • 使用了set注入后, 程序不再具有主动性, 而是变成了被动的接收对象
  • 这种思想, 从本质上解决了问题, 我们程序员不用再去管理对象的创建了, 系统的耦合度大大降低, 可以更加专注在业务的实现上! 这是IOC的原型!

<bean id="user" class="com.dz.entity.User">
    <property name="name" value="张三"/>
    <property name="age" value="18"/>
    <property name="gender" value="true"/>
bean>

<bean id="user" class="com.dz.entity.User">
    <constructor-arg index="0" value="张三"/>
    <constructor-arg index="1" value="18"/>
    <constructor-arg index="2" value="true"/>
bean>

<bean id="user" class="com.dz.entity.User">
    <constructor-arg type="java.lang.String" value="张三"/>
    <constructor-arg type="java.lang.Integer" value="18"/>
    <constructor-arg type="java.lang.Boolean" value="true"/>
bean>

<bean id="user" class="com.dz.entity.User">
    <constructor-arg name="name" value="张三"/>
    <constructor-arg name="age" value="18"/>
    <constructor-arg name="gender" value="true"/>
bean>
  • 总结: 在配置文件加载的时候, 容器中管理的对象就已经初始化了

<alias name="user" alias="userNew"/>

<bean id="user" class="com.dz.entity.User" name="user2 user3,user4;user5">
    <property name="name" value="张三"/>
    <property name="age" value="18"/>
    <property name="gender" value="true"/>
bean>

<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="beans.xml"/>
    <import resource="beans2.xml"/>
beans>
  • 依赖注入: Set注入!

  • 依赖: bean对象的创建依赖于容器

  • 注入: bean对象中的所有属性, 由容器来注入

环境搭建

package com.dz.entity;

public class Address {
    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}
package com.dz.entity;

import java.util.*;

public class Student {
    private String name;
    private Address address;
    private String[] books;
    private List hobbies;
    private Map card;
    private Set games;
    private String wife;
    private Properties info;

}

<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="student" class="com.dz.entity.Student">
        <property name="name" value="张三"/>
    bean>
beans>
import com.dz.entity.Student;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

        Student student = context.getBean("student",Student.class);
        System.out.println(student.getName());
    }
}

完善注入信息


<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="address" class="com.dz.entity.Address">
        <property name="address" value="郑州"/>
    bean>

    <bean id="student" class="com.dz.entity.Student">

        <property name="name" value="张三"/>

        <property name="address" ref="address"/>

        <property name="books">
            <array>
                <value>红楼梦value>
                <value>西游记value>
                <value>三国演义value>
                <value>水浒传value>
            array>
        property>

        <property name="hobbies">
            <list>
                <value>看书value>
                <value>游戏value>
                <value>看剧value>
            list>
        property>

        <property name="card">
            <map>
                <entry key="身份证" value="123456"/>
                <entry key="银行卡" value="123456"/>
            map>
        property>

        <property name="games">
            <set>
                <value>lolvalue>
                <value>cfvalue>
            set>
        property>

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

        <property name="info">
            <props>
                <prop key="driverClassName">com.mysql.jdbc.Driverprop>
                <prop key="url">jdbc:mysql://localhost:3306/prop>
                <prop key="username">rootprop>
                <prop key="password">8031prop>
            props>
        property>
    bean>
beans>

  • 我们可以使用p命名空间和c命令空间进行注入

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

    <bean id="user" class="com.dz.entity.User" p:name="张三" p:age="18"/>

    <bean id="user2" class="com.dz.entity.User" c:name="李四" c:age="19"/>
beans>

public void test2() {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
    User user = context.getBean("user2",User.class);
    System.out.println(user.toString());
}
  • 注意: p命名和c命名空间不能直接使用, 需要导入xml约束
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
<bean id="user" class="com.dz.entity.User" p:name="张三" p:age="18" scope="singleton"/>
<bean id="user2" class="com.dz.entity.User" c:name="李四" c:age="19" scope="prototype"/>
  • 自动装配是Spring满足bean依赖的一种方式
  • Spring会在上下文中自动寻找, 并自动给bean装配属性

在Spring中有三种自动装配的方式

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


<bean id="person" class="com.dz.entity.Person" autowire="byName">
    <property name="name" value="张三"/>
bean>

<bean id="person" class="com.dz.entity.Person" autowire="byType">
    <property name="name" value="张三"/>
bean>

小结:

  • byName的时候, 需要保证所有bean的id唯一, 且这个bean的 id需要和自己对象属性名相同
  • byType的时候, 需要保证所有bean的class唯一, 且这个bean需要和自己对象属性的类别相同

  • jdk1.5支持的注解, Spring2.5就支持注解了

  • 使用注解须知:
  • 导入约束. context约束
  • 配置注解的支持 < context:annotation-config />
  • 下方的配置是使用注解前需要导入的

<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>
  • 直接在属性上使用即可

科普:

  • @nullable: 字段标记了这个注解, 说明这个字段可以为nul
public  Autowired {
    boolean required() default true;
}

测试代码

public class Person {

    private Dog dog;

    private Cat cat;
    private String name;
}
  • 如果@Autowired自动装配的环境比较复杂, 自动装配无法通过一个注解(@Autowired) 完成的时候, 可以使用 @Qualifier(value=”xxx”)去配合@Autowired, 指定一个唯一的bean对象注入
public class Person {

    private Dog dog;

    private Cat cat;
    private String name;
}
public class Person {

    private Dog dog;

    private Cat cat;
    private String name;

小结:

@Resource和@Autowired的区别:

  • 都是用来自动装配的, 都可以放在属性字段上
  • @Autowired通过byType实现 [常用]
  • @Resource默认通过byName实现, 如果找不到名字, 则通过byType实现, 如果类型也找不到, 就报错! [常用]
  • 执行顺序不同: @Autowired通过byType实现. @Resource默认通过byName实现

  • 在Spring4之后, 想要使用注解开发, 必须要保证 aop 的包已导入

  • 使用注解需要
  • 导入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:component-scan base-package="com.dz"/>

beans>
  • 我们现在完全不使用Spring的xml配置了, 全权交给Java来做
  • JavaConfig 是Spring的一个子项目, 在Spring4之后, 它称为了一个核心功能

实体类

package com.dz.pojo;

import org.springframework.beans.factory.annotation.Value;

public class User {

    private String name;

    public String getName() {
        return name;
    }

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

配置文件

package com.dz.config;

import com.dz.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

public class AppConfig {

    public User user() {
        return new User();
    }
}

测试类

import com.dz.config.AppConfig;
import com.dz.pojo.User;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        User user = (User) context.getBean("user");
        System.out.println(user.getName());
    }
}

为什么要学习代理模式? 因为这就是SpringAOP的底层?

[SpringAOP 和 SpringMVC 面试必问]

代理模式的分类:

  • 静态代理
  • 动态代理

角色分析:

代码步骤:

  • 接口
package com.dz.demo01;

public interface Rent {
    void rent();
}
  • 真实角色
package com.dz.demo01;

public class Landlord implements Rent{

    public void rent() {
        System.out.println("房东要出租房子!");
    }
}
  • 代理角色
package com.dz.demo01;

public class Proxy implements Rent{
    private Landlord landlord;

    public Proxy() {
    }

    public Proxy(Landlord landlord) {
        this.landlord = landlord;
    }

    public void rent() {
        landlord.rent();
    }

    public void seeHouse() {
        System.out.println("中介带你去看房");
    }

    public void charge() {
        System.out.println("中介收中介费");
    }
}
  • 客户访问代理角色
package com.dz.demo01;

public class Tenant {
    public static void main(String[] args) {

        Landlord landlord = new Landlord();

        Proxy proxy = new Proxy(landlord);

        proxy.rent();
    }
}

代理模式的优点:

  • 可以使真实角色的操作更加纯粹, 不用去关注一些公共的业务
  • 公共也就是交给了代理角色, 实现了业务的分工
  • 公共业务发生扩展的时候, 方便集中管理

缺点:

  • 一个真实角色就会产生一个代理角色; 代码量会翻倍, 开发效率会变低

  • 在不改变原有代码的基础上, 又通过代理增加了新的功能

  • 动态代理和静态代理角色一样

  • 动态代理的代理类是动态生成的, 不是我们直接写好的
  • 动态代理分为两大类:
  • 基于接口—JDK代理[我们一般使用这个]
  • 基于类: cglib
  • java 字节码实现: javasist

Proxy类 和 InvocationHandler接口

  • Proxy提供了创建动态代理类和实例的静态方法, 我们最常用的是newProxyInstance方法, 这个方法接收以下三个参数
  • loader:一个classloader对象,定义了由哪个classloader对象对生成的代理类进行加载
  • interfaces:一个interface对象数组,表示我们将要给我们的代理对象提供一组什么样的接口,如果我们提供了这样一个接口对象数组,那么也就是声明了代理类实现了这些接口,代理类就可以调用接口中声明的所有方法。
  • h:一个InvocationHandler对象,表示的是当动态代理对象调用方法的时候会关联到哪一个InvocationHandler对象上,并最终由其调用。
  • InvocationHandler接口是proxy代理实例的调用处理程序实现的一个接口,每一个proxy代理实例都有一个关联的调用处理程序;在代理实例调用方法时,方法调用被编码分派到调用处理程序的invoke方法。

动态代理的好处:

  • 可以使真实角色的操作更加纯粹, 不用去关注一些公共的业务
  • 公共也就是交给了代理角色, 实现了业务的分工
  • 公共业务发生扩展的时候, 方便集中管理
  • 一个动态代理类代理的是一个接口, 一般就是对应的一类业务
  • 一个动态代理类可以代理多个类, 只要是实现了同一个接口即可

动态代理实现:

package com.dz.demo04;

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

public class ProxyInvocationHandler implements InvocationHandler {

    private 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 {
        log(method.getName());

        Object result = method.invoke(target, args);
        return result;
    }

    public void log(String msg) {
        System.out.println("执行了" + msg + "方法");
    }
}

测试:

package com.dz.demo04;

import com.dz.demo02.UserService;
import com.dz.demo02.UserServiceImpl;

public class Client {
    public static void main(String[] args) {

        UserService userService = new UserServiceImpl();

        ProxyInvocationHandler pih = new ProxyInvocationHandler();

        pih.setTarget(userService);

        UserService proxy = (UserService) pih.getProxy();

        proxy.insert();
    }
}
  • 在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

  • 将日志记录,性能统计,安全控制,事务处理, 异常处理 等代码从业务逻辑代码中划分出来,通过对这些行为的分离,我们希望可以将它们独立到非指导业务逻辑的方法中,进而改变这些行为的时候不影响业务逻辑的代码。

  • Aspect(切面): Aspect 声明类似于 Java 中的类声明,在 Aspect 中会包含着一些 Pointcut 以及相应的 Advice。
  • Joint point(连接点):表示在程序中明确定义的点,典型的包括方法调用,对类成员的访问以及异常处理程序块的执行等等,它自身还可以嵌套其它 joint point。
  • Pointcut(切点):表示一组 joint point,这些 joint point 或是通过逻辑关系组合起来,或是通过通配、正则表达式等方式集中起来,它定义了相应的 Advice 将要发生的地方。
  • Advice(增强):Advice 定义了在 Pointcut 里面定义的程序点具体要做的操作,它通过 before、after 和 around 来区别是在每个 joint point 之前、之后还是代替执行的代码。
  • Target(目标对象):织入 Advice 的目标对象.。
  • Weaving(织入):将 Aspect 和其他对象连接起来, 并创建 Adviced object 的过程
<dependency>
    <groupId>org.aspectjgroupId>
    <artifactId>aspectjweaverartifactId>
    <version>1.9.6version>
dependency>
<bean id="userService" class="com.dz.service.UserServiceImpl"/>
<bean id="beforeLog" class="com.dz.log.BeforeLog"/>
<bean id="afterLog" class="com.dz.log.AfterLog"/>

<aop:config>

    <aop:pointcut id="pointcut" expression="execution(* com.dz.service.UserServiceImpl.*(..))"/>

    <aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/>
    <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
aop:config>
<bean id="diy" class="com.dz.diy.DiyPointCut"/>

<aop:config>

    <aop:aspect ref="diy">

        <aop:pointcut id="pointcut" expression="execution(* com.dz.service.UserServiceImpl.*(..))"/>

        <aop:before method="before" pointcut-ref="pointcut"/>
        <aop:after method="after" pointcut-ref="pointcut"/>
    aop:aspect>
aop:config>

<bean id="annotationPointCut" class="com.dz.diy.AnnotationPointCut"/>

<aop:aspectj-autoproxy/>

package com.dz.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 AnnotationPointCut {

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

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

    @Around("execution(* com.dz.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("====环绕前====");
        Signature signature = pjp.getSignature();//获得签名
        System.out.println(signature);
        Object proceed = pjp.proceed(); //执行方法
        System.out.println("====环绕后====");
    }
}
  • 步骤
  • 导入相关jar包
    • junit 4.12
    • mysql-connector-java 5.1.47
    • mybatis 3.5.3
    • spring相关的 (spring-webmvc 5.3.5, spring-jdbc 5.3.5)
    • aop织入(aspectjweaver 1.96)
    • mybatis-spring 2.06
    • lombok 1.18.16
  • 编写配置文件
  • 测试
<dependency>
    <groupId>org.projectlombokgroupId>
    <artifactId>lombokartifactId>
    <version>1.18.16version>
    <scope>providedscope>
dependency>
  • 编写实体类
  • 编写核心配置文件 mybatis-config.xml ,主要配置:
  • 导入 jdbc.properties数据库连接配置文件
  • 设置实体类别名
  • 环境配置: 数据库事务控制类型, 连接池
  • 注册mapper文件
  • 编写接口
  • 编写Mapper.xml
  • 编写MyBatis工具类并测试

  • 事务(Transaction),一般是指要做的或所做的事情。在计算机术语中是指访问并可能更新数据库中各种数据项的一个程序执行单元(unit)。事务通常由高级数据库操纵语言或编程语言(如SQL,C++或Java)书写的用户程序的执行所引起,并用形如 begin transactionend transaction语句(或函数调用)来界定。事务由事务开始(begin transaction)和事务结束(end transaction)之间执行的全体操作组成。

  • 事务是恢复和并发控制的基本单位。
  • 事务应该具有4个属性:原子性、一致性、隔离性、持久性。这四个属性通常称为 ACID特性
  • 原子性(atomicity):一个事务是一个不可分割的工作单位,事务中包括的操作要么都做,要么都不做
  • 一致性(consistency):事务必须是使数据库从一个一致性状态变到另一个一致性状态。一致性与原子性是密切相关的
  • 隔离性(isolation):一个事务的执行不能被其他事务干扰。即一个事务内部的操作及使用的数据对并发的其他事务是隔离的,并发执行的各个事务之间不能互相干扰
  • 持久性(durability):持久性也称永久性(permanence),指一个事务一旦提交,它对数据库中数据的改变就应该是永久性的。接下来的其他操作或故障不应该对其有任何影响

  • 声明式事务: AOP


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

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    bean>

    <tx:advice id="txManager" transaction-manager="transactionManager">

        <tx:attributes>

            <tx:method name="inset" 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.dz.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txManager" pointcut-ref="txPointCut"/>
    aop:config>
  • 编程式事务: 需要在代码中,进行事务管理

为什么需要事务?

  • 如果不配置事务, 可能存在数据提交不一致的情况
  • 如果我们不在Spring中去配置声明式事务, 我们就要在代码中手动配置事务
  • 事务在项目的开发中十分重要, 涉及到数据的一致性和完整性问题

Original: https://www.cnblogs.com/qimu666/p/16565691.html
Author: 柒木木木
Title: 4_Spring

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/598772/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球