[spring]spring详细总结

spring

1.spring简介

  • Spring框架是一个开源的应用程序框架,是针对bean的生命周期进行管理的轻量级容器。
  • Spring解决了开发者在J2EE开发中遇到的许多常见的问题,提供了功能强大IOC、AOP及Web MVC等功能。
  • Spring可以单独应用于构筑应用程序,也可以和Struts、Webwork、Tapestry等众多Web框架组合使用,并且可以与 Swing等桌面应用程序AP组合。
  • Spring不仅仅能应用于J2EE应用程序之中,也可以应用于桌面应用程序以及小应用程序之中。
  • Spring框架主要由七部分组成,分别是 Spring Core、 Spring AOP、 Spring ORM、 Spring DAO、Spring Context、 Spring Web和 Spring Web MVC。

官方文档地址:

https://docs.spring.io/spring-framework/docs/4.3.9.RELEASE/spring-framework-reference/

https://docs.spring.io/spring-framework/docs/5.2.0.RELEASE/spring-framework-reference/core.html#spring-core

中文

https://www.docs4dev.com/docs/zh/spring-framework/5.1.3.RELEASE/reference/

优点:

  • 开源免费
  • 轻量级的非入侵式的
  • 控制反转(IOC),面向切面编程(aop)
  • 支持事务处理

使用spring的jar包支持:


    org.springframework
    spring-web
    5.3.22

七大模块:

[spring]spring详细总结

弊端:发展了太久后,配置越来越多,人称”配置地狱”

2.IOC理论推导

在我们之前的业务中,用户的需求可能会影响程序的代码,可能需要修改代码,如果程序的代码量十分大,修改一次的成本十分的昂贵!

原来的方式:

private UserMapper usermapper=new UserMapperImpl();

现在将对象的传递由new变成set动态注入

private UserMapper userMapper;
public void setUserMapper(UserMapper userMapper){
    this.userMapper=userMapper;
}

原来是程序控制的,现在变成用户控制了。

3.一个spring项目的快速搭建

(1)写一个实体类

package com.pojo;

/**
 * @author panglili
 * @create 2022-07-23-21:40
 */
public class HelloSpring {
    private String name;

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

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return name;
    }
}

(2)将实体类配置在spring容器


(3)测试

import com.pojo.HelloSpring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author panglili
 * @create 2022-07-23-21:43
 */
public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext( "application.xml");
        HelloSpring hello =(HelloSpring) context.getBean("helloSpring");
        System.out.println(hello.toString());

    }
}

4.IOC创建对象的过程

  • 使用无参构造创造

[spring]spring详细总结

[spring]spring详细总结

设定为有参后,就会报错!

对象在被注册进去的时候,就被实例化了,直接使用就好。

5.IO注入

(1)前面的构造器注入

(2)set注入


构造注入对象之间的关系为组合

set注入的对象之间的关系为聚合

(3)p命名空间注入

  • 使用set方式注入

(4)c命名空间注入

  • 使用构造器方式注入,开启构造器才能用
HelloSpring(String name){
    this.name=name;
}
HelloSpring(){

}

注意导入头文件

xmlns:p = "http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"

6.作用域

ScopeDescription

singleton

(Default) Scopes a single bean definition to a single object instance for each Spring IoC container.

prototype

Scopes a single bean definition to any number of object instances.

request

Scopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

session

Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

application

Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.

websocket

Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.

  • 单例

**

  • 原型

7.bean的自动装配

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

spring的装配方式:

(1)手动装配

  • 在people类中依赖了cat和dog对象,所以属性中手动装配他们的属性

(2)自动装配

通过byName自动装配

  • spring会自动去找people中的set后面相对应的cat和dog与bean中id对应

通过byType自动装配

  • spring会自动去找people中的对象依赖和bean中class类相同的对应

(3)使用注解实现自动装配

使用之前导入注解依赖的配置和支持


不再使用显示引用对象依赖的其他属性


@Autowired

直接在对象上面使用@Autowired注解

private String name;
@Autowired
private Dog dog;
@Autowired
private Cat cat;

如果装配环境复杂的话,可以通过@Qualifier(value = “cat”)指定bean注入

例如多个cat对象bean,属性值不同的时候


就需要

@Qualifier

否则,只会spring会走第一个bean

@Autowired
@Qualifier(value = "cat11")
private Cat cat;

Resource

  • 这个注解跟上面的@Autowired功能相似,但是它可以通过名字再通过类型装配,都没有才会报错,要比@Autowired智能一点,但使用较少。
@Resource(name="cat")
private Cat cat;

8.使用注解开发

1.bean

spring4以后,注解依赖于aop包,确保你的lib中有它

[spring]spring详细总结

确保开启了使用注解


2.组件代替bean实现自动注入

在配置文件中自动扫描包下的所有类为bean


在类对象上加上注解@Component可以被扫描

  • @component (把普通pojo实例化到spring容器中,相当于配置文件中的 )
@Component

使用注解给属性注入值

package pojo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author panglili
 * @create 2022-07-24-9:52
 */
@Component
public class People {
    private String name;
    @Value("123")
   public int age;
    private Dog dog;
    private Cat cat;
 }
}
  • 但是复杂的属性配置还是建议使用xml统一管理注入

3.component衍生的注解

dao:@repository

service:@service

controller:@controller

跟component功能相同只是能够使得分工更加的明确

小结:

xml与注解:

  • xml更加万能,适用于各种场合!维护简单方便
  • 注解 不是自己类使用不了,维护相对复杂

最佳实践:

  • xml用来管理bean
  • 注解只负责属性的注入

9.使用javaconfig实现代替xml配置

The central artifacts in Spring’s new Java-configuration support are @Configuration -annotated classes and @Bean -annotated methods.

根据官方文档的说明,创建一个java—configuration的配置类,使用@configuration注解,再使用@Bean在方法上面就可以实现xml中的功能。

(1)创建一个java—configuration

package config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import pojo.User;

/**
 * @author panglili
 * @create 2022-07-24-11:24
 */
@Configuration
public class Java_config {

    @Bean
    public User getUser(){
        return new User();
    }
}

(2)实体类

package pojo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * @author panglili
 * @create 2022-07-24-11:24
 */
@Component
public class User {
    @Value("tata")
    private String name;

    public String getName() {
        return name;
    }

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

(3)测试

现在也可以拿到值

import config.Java_config;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import pojo.User;

/**
 * @author panglili
 * @create 2022-07-24-11:28
 */
public class MyTest {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Java_config.class);
        User user =(User) context.getBean("getUser");

        System.out.println(user.getName());
    }
}

[spring]spring详细总结

这种java代替xml的实现方式,在springboot中大量使用。

10.代理模式

代理模式的分类:

  • 静态代理
  • 动态代理

关系分析

[spring]spring详细总结

抽象角色:一般会使用接口或者抽象类

真实角色:被代理的角色

代理角色:代理真实的角色,做一些附属的操作

客户:访问代理对象的人

静态代理

步骤:

抽象角色:

/**
 * @author panglili
 * @create 2022-07-24-15:00
 */
public interface Rent {
    public void rent();
}

真实角色:

/**
 * @author panglili
 * @create 2022-07-24-15:01
 */
public class Host implements Rent {
    public void rent() {
        System.out.println("host would rent house");

    }
}

代理角色:

/**
 * @author panglili
 * @create 2022-07-24-15:02
 */
public class Proxy implements Rent {

    private Host host;
    public Proxy(){

    }

    public Proxy(Host host){
        this.host=host;
    }

    public void rent() {
        host.rent();
        seeHouse();
    }

    //look house
    public void seeHouse(){
        System.out.println("look House");
    }
}

客户:

/**
 * @author panglili
 * @create 2022-07-24-15:02
 */
public class Client  {
    public static void main(String[] args) {
        Host host = new Host();
        Proxy proxy = new Proxy(host);
        proxy .rent();
    }
}

动态代理

  • 和静态代理的角色一样
  • 动态生成,不是我们直接写好了的
  • 动态代理分为两大类:基于接口的动态代理和基于类的动态代理
  • 基于接口——jdbc
  • 基于类——cglib
  • 基于字节码

11.AOP切面编程

使用aop植入,需要导入一个依赖包


    org.aspectj
    aspectjweaver
    1.9.7

  • 横切关注点
  • 切面
  • 通知
  • 目标
  • 代理
  • 切入点
  • 连接点

在执行的方法前动态的添加一个日志输出

方法一使用spring类实现

(1)接口

package service;

/**
 * @author panglili
 * @create 2022-07-24-16:09
 */
public interface Service {
    public void add();
    public void delete();
    public void update();
    public void select();
}

(2)要代理的实现类

package service;

/**
 * @author panglili
 * @create 2022-07-24-16:09
 */
public class ServiceImpl implements Service {
    public void add() {
        System.out.println("add");
    }

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

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

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

(3)代理商

package log;

import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

/**
 * @author panglili
 * @create 2022-07-24-16:11
 */
public class Log implements MethodBeforeAdvice {
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println("excutor"+method.getName()+target);
    }
}

(4)客户调用

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.Service;

/**
 * @author panglili
 * @create 2022-07-24-16:28
 */
public class MyTest  {
    public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
        //注意,代理的是接口类型
        Service ser = (Service) context.getBean("userSer");
        ser.add();

    }
}

方法二 使用自定义类实现

(1)自定义一个类,是被横切进去的内容

package dir;

/**
 * @author panglili
 * @create 2022-07-24-17:00
 */
public class PointMethod {
    public void after(){
        System.out.println("执行方法之后切入......");
    }
    public void before(){
        System.out.println("执行方法之前切入......");
    }
}

(2)在配置文件中使用aop切入


(3)测试

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.Service;

/**
 * @author panglili
 * @create 2022-07-24-16:28
 */
public class MyTest  {
    public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
        //注意,代理的是接口类型
        Service ser = (Service) context.getBean("userSer");
        ser.add();

    }
}

[spring]spring详细总结

方式三 使用注解实现aop

(1)在要被切入的地方使用@Aspect和@After等注解标识切面和切点等

package dir;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

/**
 * @author panglili
 * @create 2022-07-24-17:00
 */
@Aspect
public class PointMethod {
    @After("execution(* service.ServiceImpl.*(..))")
    public void after(){
        System.out.println("执行方法之后切入......");
    }
    @Before("execution(* service.ServiceImpl.*(..))")
    public void before(){
        System.out.println("执行方法之前切入......");
    }
}

(2)将此类配置到spring中,别忘了开启注解支持


(3)测试

同上面一样的测试,不再赘述

12.spring和mybatis整合

1.导包


        junit
        junit
        4.13.1

        mysql
        mysql-connector-java
        8.0.29

        org.mybatis
        mybatis
        3.5.3

        org.springframework
        spring-webmvc
        5.3.19

        org.springframework
        spring-jdbc
        5.3.18

        org.aspectj
        aspectjweaver
        1.9.7

        org.mybatis
        mybatis-spring
        2.0.2

2.将mybatis中的配置到spring中

mybatis被spring接管后,他自己的配置文件只需要写别名和日志,事务和数据库连接交给spring



3.接口实现类

package mapper;

import org.mybatis.spring.SqlSessionTemplate;
import pojo.User;

import java.util.List;

/**
 * @author panglili
 * @create 2022-07-24-18:42
 */
public class UserMapperImpl implements UserMapper {
    private SqlSessionTemplate sqlSession;

    public void setSession(SqlSessionTemplate session) {
        this.sqlSession = session;
    }

    public List user() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        return mapper.user();
    }
}

测试

import mapper.UserMapper;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pojo.User;
import java.util.List;

/**
 * @author panglili
 * @create 2022-07-24-18:01
 */
public class MyTest {
  @Test
    public void Test(){

       ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
        UserMapper user1 = context.getBean("user", UserMapper.class);
        List list = user1.user();
        for(User u :list){
            System.out.println(u);
        }

    }
}

13.事务支持

只需要在spring中简单的配置两点就可以实现


注意代理的是接口不是类!!!


Original: https://www.cnblogs.com/lumanmanqixiuyuanxi/p/16544483.html
Author: 路漫漫qixiuyuanxi
Title: [spring]spring详细总结

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

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

(0)

大家都在看

  • MySQL8.0 DDL原子性特性

    1. DDL原子性概述 8.0之前并没有统一的数据字典dd,server层和引擎层各有一套元数据,sever层的元数据包括(.frm,.opt,.par,.trg等),用于存储表定…

    数据库 2023年6月9日
    061
  • 小心陷入MySQL索引的坑

    索引可以说是数据库中的一个大心脏了,如果说一个数据库少了索引,那么数据库本身存在的意义就不大了,和普通的文件没什么两样。所以说一个好的索引对数据库系统尤其重要,今天来说说MySQL…

    数据库 2023年6月6日
    097
  • try enabling the break write locks option for the cleanup

    如图: 一般是在中断:提交/更新的时候产生的。 一般两种解决方式(可以参考其他的): 1,重启ide(我的就是这么神奇,重启idea后好了); 2,在cleanup时勾选 brea…

    数据库 2023年6月11日
    0127
  • 事物的隔离性和MVCC

    事物的隔离性 mysql的服务端是支持多个客户端同时与之连接的,每个客户端可能还并发了好几个连接,所以mysql是需要同时处理很多事情的,每一件独立的事情就叫做事务。我们知道事务有…

    数据库 2023年5月24日
    093
  • 2022-8-24 js

    JavaScript脚本语言,解释性 主要给HTML网页&#x…

    数据库 2023年6月14日
    087
  • 数据库

    建库操作 #创建数据库(默认字符集编码) create database test20210420 #创建数据库的时候指定字符集编码以及字符校验规则 create database…

    数据库 2023年6月16日
    0129
  • Kafka集群部署

    404. 抱歉,您访问的资源不存在。 可能是网址有误,或者对应的内容被删除,或者处于私有状态。 代码改变世界,联系邮箱 contact@cnblogs.com 园子的商业化努力-困…

    数据库 2023年6月16日
    081
  • zabbix自定义监控(mysql主从状态和延迟)

    zabbix自定义监控 需要先配置mysql主从,从库上需要安装zabbix_agentdzabbix_server配置zabbix_agentd配置mysql主从配置 监控mys…

    数据库 2023年6月14日
    084
  • 了解HTML/CSS/JS/JQuery/ajax等前端知识

    什么是HTML 超文本标记语言 浏览器通过识别相应的标签来加载页面 通过HTTP协议传输,不是编程语言 HTML常用标签 title script style link meta …

    数据库 2023年6月16日
    0140
  • SQL的语法

    创建: create database [if not exists] 数据库名称 [default charset 字符集] [collate 排序规则]; (PS:方括号(&#…

    数据库 2023年6月16日
    087
  • tomcat部署war包 首页面默认展示自己定义的页面

    将项目war包部署到tomcat的webapps后,http://localhost:8080 展示tomcat页面,http://localhost:8080/appName展示…

    数据库 2023年6月16日
    083
  • Mysql_视图

    视图是指计算机数据库中的视图,是一个虚拟表,其内容由查询定义。同真实的表一样,视图包含一系列带有名称的列和行数据。但是,视图并不在数据库中以存储的数据值集形式存在。行和列数据来自由…

    数据库 2023年6月11日
    093
  • Java百度地图经纬度纠偏

    在国内使用电子地图获取到的经纬度都不是真实的经纬度,而是经过一定的算法在真实的经纬度上添加了一个偏移量,且不同的地图有不同的算法。现在告诉大家在java中怎样对百度地图进行纠偏,主…

    数据库 2023年6月9日
    090
  • Mysql 手册

    MySQL是一个关系型数据库管理系统,由瑞典MySQL AB 公司开发,属于 Oracle 旗下产品。MySQL 是最流行的关系型数据库管理系统之一,在 WEB 应用方面,MySQ…

    数据库 2023年5月24日
    0122
  • go的调度

    操作系统根据资源访问权限的不同,体系架构可以分为用户空间和内核空间;内核空间主要操作访问CPU资源,IO资源,内存资源等硬件资源,为应用程序提供最基本的基础资源;用户空间是上层应用…

    数据库 2023年6月9日
    084
  • day02-MySQL基础知识

    MySQL基本知识 1.数据库 1.1.创建数据库 语法: CREATE DATABASE [IF NOT EXISTS] db_name [create_specificatio…

    数据库 2023年6月11日
    096
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球