[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)

大家都在看

  • MySQL查询性能优化七种武器之索引下推

    前面已经讲了MySQL的其他查询性能优化方式,没看过可以去了解一下: MySQL查询性能优化七种武器之索引潜水 MySQL查询性能优化七种武器之链路追踪 今天要讲的是MySQL的另…

    数据库 2023年5月24日
    088
  • 升级JDK8的坎坷之路

    为更好的适应JAVA技术的发展,使用更先进及前沿的技术。所以推出将我们现在使用的JDK1.6(1.7)及tomcat6(7)升级至JDK1.8及tomcat8,使我们的系统获得更好…

    数据库 2023年6月6日
    080
  • Mysql之Binlog

    1、简述 binlog 二进制日志文件,这个文件记录了MySQL所有的DML操作。通过binlog日志我们可以做数据恢复,增量备份,主主复制和主从复制等等。 2、Docker中无法…

    数据库 2023年5月24日
    0117
  • 正则表达式与SQL

    在我心中正则表达式和SQL就是一样的东西。 SQL是结构化查询语言,是根据某个查询、修改规则来查询修改数据,是描述一个规则给数据库,数据库来执行,数据库返回结果,过程不需要考虑,不…

    数据库 2023年6月9日
    062
  • Java中AES加密和解密的方法分享

    转自: http://www.java265.com/JavaJingYan/202206/16559759223818.html 下文笔者讲述java代码实现的AES加密和解密的…

    数据库 2023年6月11日
    088
  • 23种设计模式之命令模式和策略模式的区别

    命令模式和 策略模式确实很相似,只是命令模式多了一个接收者(Receiver)角色。它们虽然同为行为类模式,但是两者的区别还是很明显的。策略模式的意图是封装算法,它认为&#8221…

    数据库 2023年6月6日
    076
  • Linux进程管理

    进程管理 基本概念介绍 进程和线程 进程: 一个在内存中运行的应用程序,每一个进程都有自己独立的一块内存空间,并被分配一个ID号(PID),在Windows下可以打开任务管理器查看…

    数据库 2023年6月16日
    0100
  • 【中国信通院 x ShardingSphere 金融用户社区】成立,多家知名金融机构正式入驻

    2022 年 5 月 20 日”OSCAR 开源先锋日”现场,Apache ShardingSphere 联合中国信通院共同成立了【中国信通院 x Shar…

    数据库 2023年6月16日
    083
  • Mybatis的级联查询,分步查询,一对一,一对多和多对一

    配置和代码目录 ***util配置 ***log4j配置 –可以打印入日志,也可以使用系统自带的STDOUT_LOGGING个人喜欢log4j ***mybatis-c…

    数据库 2023年6月16日
    074
  • Sql的字符串匹配 like

    患者信息表: Patients +————–+———+ | Column Name | Type | +————–+——–…

    数据库 2023年6月14日
    075
  • 0. 数据库设计规范化

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

    数据库 2023年6月16日
    090
  • 运行jar包使用外部依赖

    nohup java -Dloader.path=”lib/” -Dfile.encoding=utf-8 -jar test.jar > test….

    数据库 2023年6月9日
    052
  • 云数据库技术行业动态@2022-09-30

    重要更新 时序数据库厂商「格睿云Greptime」已于近期完成天使轮融资。据介绍,本轮融资金额在数百万美金级别,由耀途资本领投,九合创投跟投。Greptime成立于2022年4月,…

    数据库 2023年6月11日
    0101
  • 图片防盗链

    如何避免别的网站直接通过本网站的url访问本网站资源 简单的防盗 我可以做到请求来的时候先看看当前请求是从哪个网站过来的如果是本网站那么正常访问如果是其他网站直接拒绝请求头里面有一…

    数据库 2023年6月14日
    071
  • javaweb之HttpSession对象

    1.session会话追踪原理 客户端第一次请求服务端,服务端会创建一个session对象并且存储下来,之后会将session的唯一标识sessionId设置到响应头中传给客户端 …

    数据库 2023年6月16日
    072
  • docker-ckeditor图片img标签style属性自适应

    1,修改ckeditor的源码cofig.js文件 // 不给图片img&#x6DF…

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