Spring中注入bean时的scope属性详解、往singleton中注入prototype属性的bean以及Spring使用注解实现AOP切面编程

news2024/10/4 14:19:21

一、Spring中注入bean时的scope属性详解以及往singleton中注入prototype属性的bean

        官方文档上提到Spring中scope属性可以有以下取值:

1. singleton : (Default) Scopes a single bean definition to a single object instance for each Spring IoC container.
singleton (单一实例)容器中创建时只存在一个实例,也就是单例模型。

2. prototype : Scopes a single bean definition to any number of object instances.
prototype 容器在输出bean对象时,每次都会重新生成一个新的对象给请求方。

3. 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.
request 容器XmlWebApplicationContext 会为每个HTTP请求创建一个全新的RequestPrecessor对象,请求结束该对象的生命周期结束,可以认为在浏览器每次刷新都会生成一个新的bean。

4. session : Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
session 可以理解为用户的登录信息,Spring容器会为每个独立的session创建属于自己的全新的实例,比request存活更长时间。可以理解为一个用户使用浏览器请求每次刷新时都是相同的bean.

5. application : Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.
ServletContext(web应用)中的单例,在一个web应用中,可能会有多个ApplicationContext,所以,application不等于singleton(singleton是容器中的单例)。可以理解为不同的用户刷新同一个请求(调用同一个application)都是相同的bean.

6. websocket : Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext。即WebSocket的完整生命周期中将创建并提供一个实例。

    虽然属性值不少,不过常用的也就是singleton和prototype。除了在配置文件中设置scope属性外,还可以在类中使用scope注解实现。request,session和global session只用于web程序,比如和XmlWebApplicationContext共同使用。

        如下示例,而如果在非WEB程序中使用request就会报异常:Exception in thread "main" java.lang.IllegalStateException: No Scope registered for scope name 'request'

package com.kermit.test;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype")
//@Scope("singleton")
//@Scope("request")
public class HelpTool {
    public String getString(){
        return "spring.";
    }
}

    另外注意到spring文档中1.5.3.关于Singleton Beans with Prototype-bean Dependencies的描述:

    When you use singleton-scoped beans with dependencies on prototype beans, be aware that dependencies are resolved at instantiation time. Thus, if you dependency-inject a prototype-scoped bean into a singleton-scoped bean, a new prototype bean is instantiated and then dependency-injected into the singleton bean. The prototype instance is the sole instance that is ever supplied to the singleton-scoped bean.

    However, suppose you want the singleton-scoped bean to acquire a new instance of the prototype-scoped bean repeatedly at runtime. You cannot dependency-inject a prototype-scoped bean into your singleton bean, because that injection occurs only once, when the Spring container instantiates the singleton bean and resolves and injects its dependencies. If you need a new instance of a prototype bean at runtime more than once, see Method Injection。

    即要在一个singleton的bean中注入一个prototype的bean,这个prototype的bean只会初始化一次,因为在注入操作时prototype的bean已经完成了初始化,因为prototype的作用不会生效。如果要让这prototype生效,可以使用Method Injection方法注入。

二、Spring使用注解实现AOP切面编程

        Spring使用注解实现AOP切面编程首先需要导入一些包,在测试的时候,我开始使用@Aspect注解时,就是找不到 import 包,后来发现是缺少包:aspectj 导致的问题。我这里导入的包如下:

<dependencies>
	<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-webmvc</artifactId>
		<version>5.3.39</version>
	</dependency>

	<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
	<dependency>
		<groupId>org.aspectj</groupId>
		<artifactId>aspectjweaver</artifactId>
		<version>1.9.9</version>
		<scope>runtime</scope>
	</dependency>

	<!-- https://mvnrepository.com/artifact/aspectj/aspectjrt -->
	<dependency>
		<groupId>aspectj</groupId>
		<artifactId>aspectjrt</artifactId>
		<version>1.5.4</version>
	</dependency>
</dependencies>

        ApplicationContext.xml 配置文件中需要添加上注解支持的配置,在使用 <aop:aspectj-autoproxy /> 配置时,其有一个属性  proxy-target-class="" 值默认为False 即为使用JDK实现注解,如果修改为True,则表示使用cglib来实现,但这些对用户无感,也无须关注,知道即可。

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


    <!--注解AOP-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

</beans>

        切入的方法类及注解内容如下代码所示:

package com.kermit.aoptest;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class DiyLog  {

    @Before(value = "execution(* com.kermit.aoptest.Article.*(..))")
    public void before(){
        System.out.println("do before method");
    }

    @After(value = "execution(* com.kermit.aoptest.Article.*(..))")
    public void after(){
        System.out.println("do after method");
    }

}

被切入的类方法代码如下:

package com.kermit.aoptest;

import org.springframework.stereotype.Component;

import java.sql.SQLOutput;
@Component
public class Article implements ArticleInterface{
    @Override
    public void insert() {
        System.out.println("insert one record.");
    }

    @Override
    public void update() {
        System.out.println("update one record.");
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2188166.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Gazebo环境下开源UAV与USV联合仿真平台

推荐一个ROS2下基于Gazebo环境的开源UAV与USV联合仿真平台。平台是由两个开源项目共同搭建的。首先是UAV仿真平台&#xff0c;是基于PX4官方仿真平台&#xff08;https://docs.px4.io/main/en/sim_gazebo_gz&#xff09;&#xff1b;其次是USV仿真平台&#xff0c;是基于VRX仿真…

C++语言学习(4): identifier 的概念

1. 什么是 identifier identifier 中文意思是标识符&#xff0c;在 cppreference 中明确提到&#xff0c;identifier 是任意长度的数字、下划线、大写字母、小写字母、unicode 字符 的序列&#xff1a; An identifier is an arbitrarily long sequence of digits, underscores…

FBX福币历史重演,ETH可能会在第四季度出现熊市

知名加密货币分析师Benjamin Cowen警告称&#xff0c;以太坊(ETH)可能在今年最后三个月突然转为看跌。FBX福币凭借用户友好的界面和对透明度的承诺,迅速在加密货币市场中崭露头角,成为广大用户信赖的平台。 考恩告诉他在社交媒体平台十、上的861500名粉丝表示&#xff0c;ETH可…

240 搜索二维矩阵 II

解题思路&#xff1a; \qquad 解这道题最重要的是如何利用从左到右、从上到下为升序的性质&#xff0c;快速找到目标元素。 \qquad 如果从左上角开始查找&#xff0c;如果当前matrix[i][[j] < target&#xff0c;可以向右、向下扩展元素都是升序&#xff0c;但选择哪个方向…

Python+Matplotlib创建高等数学上册P2页例2交互动画

import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Slider, CheckButtons# 创建图形和坐标轴 fig, ax plt.subplots(figsize(10, 8)) plt.subplots_adjust(left0.1, bottom0.2)# 设置图表 ax.set_xlim([-1.5, 1.5]) ax.set_ylim([-1.5, 1.5…

C(九)while循环 --- 军训匕首操情景

匕首操&#xff0c;oi~oi~oi~~~~~ 接下来的几篇推文&#xff0c;杰哥记录的是三大循环结构的运行流程及其变式。 本篇的主角是while循环。&#x1f449; 目录&#xff1a; while循环 的组成、运行流程及其变式关键字break 和 continue 在while 循环中的作用while 循环的嵌套题目…

MySQL中NULL值是否会影响索引的使用

MySQL中NULL值是否会影响索引的使用 为何写这一篇文章 &#x1f42d;&#x1f42d;在面试的时候被问到NULL值是否会走索引的时候&#xff0c;感到有点不理解&#xff0c;于是事后就有了这篇文章 问题&#xff1a; 为name建立索引&#xff0c;name可以为空select * from user …

SpringBoot线程问题

程序&#xff0c;线程&#xff0c;线程池 进程是资源分配最小单位&#xff0c;线程是程序执行的最小单位。计算机在执行程序时&#xff0c;会为程序创建相应的进程&#xff0c;进行资源分配时&#xff0c;是以进程为单位进行相应的分配&#xff0c;每个进程都有相应的线程&…

TiDB 7.x 源码编译之 TiFlash 篇

本文首发于TiDB社区专栏&#xff1a;https://tidb.net/blog/5f3fe44d 导言 TiFlash 从去年四月一日开源至今已经过去将近一年半&#xff0c;这段时间里 TiFlash 从 v6.0.0-DMR 升级到了 v7.3.0-DMR&#xff0c;并增加了若干新特性&#xff0c;比如支持 MPP 实现窗口函数框架&am…

sql-labs靶场第五关测试报告

目录 一、测试环境 1、系统环境 2、使用工具/软件 二、测试目的 三、操作过程 1、寻找注入点 2、注入数据库 ①Order by判断列数 ②寻找注入方式 ③爆库&#xff0c;查看数据库名称 ④爆表&#xff0c;查看security库的所有表 ⑤爆列&#xff0c;查看users表的所有…

Linux之实战命令25:xargs应用实例(五十九)

简介&#xff1a; CSDN博客专家、《Android系统多媒体进阶实战》一书作者 新书发布&#xff1a;《Android系统多媒体进阶实战》&#x1f680; 优质专栏&#xff1a; Audio工程师进阶系列【原创干货持续更新中……】&#x1f680; 优质专栏&#xff1a; 多媒体系统工程师系列【…

深度优先搜索:解锁无向图连通分量的编号策略

深度优先搜索:解锁无向图连通分量的编号策略 步骤:伪代码:C 代码实现:说明:在无向图中,深度优先搜索(DFS)是一种有效的算法,可以用来找出图的连通分量(Connected Components)。DFS 遍历图的过程中,可以自然地将图划分为若干棵树,这些树构成深度优先森林,其中每棵…

day03 笔试练习

1.简写单词 题目链接&#xff1a;简写单词_牛客题霸_牛客网 public static void main(String[] args) {Scanner sc new Scanner(System.in);while(sc.hasNext()){ // 输入多少读入多少char ch sc.next().charAt(0); // 提取首字母if(ch > a && ch < z){System…

netty之SpringBoot+Netty+Elasticsearch收集日志信息数据存储

前言 将大量的业务以及用户行为数据存储起来用于分析处理&#xff0c;但是由于数据量较大且需要具备可分析功能所以将数据存储到文件系统更为合理。尤其是一些互联网高并发级应用&#xff0c;往往数据库都采用分库分表设计&#xff0c;那么将这些分散的数据通过binlog汇总到一个…

第L9周:无监督学习|K-means聚类算法

本文为365天深度学习训练营 中的学习记录博客原作者&#xff1a;K同学啊 任务描述&#xff1a; ●学会调用sklearn实现KMeans算法。 ●了解误差平方和与轮廓系数。 1.聚类算法是什么&#xff1f; 聚类就是将一个庞杂数据集中具有相似特征的数据自动归类到一起&#xff0c;称为…

Leetcode 1498. 满足条件的子序列数目

1.题目基本信息 1.1.题目描述 给你一个整数数组 nums 和一个整数 target 。 请你统计并返回 nums 中能满足其最小元素与最大元素的 和 小于或等于 target 的 非空 子序列的数目。 由于答案可能很大&#xff0c;请将结果对 109 7 取余后返回。 1.2.题目地址 https://leet…

【优选算法之队列+宽搜/优先级队列】No.14--- 经典队列+宽搜/优先级队列算法

文章目录 前言一、队列宽搜示例&#xff1a;1.1 N 叉树的层序遍历1.2 ⼆叉树的锯⻮形层序遍历1.3 ⼆叉树最⼤宽度1.4 在每个树⾏中找最⼤值 二、优先级队列&#xff08;堆&#xff09;示例&#xff1a;2.1 最后⼀块⽯头的重量2.2 数据流中的第 K ⼤元素2.3 前 K 个⾼频单词2.4 …

气象网格数据与卫星轨道数据如何匹配??

&#x1f3c6;本文收录于《全栈Bug调优(实战版)》专栏&#xff0c;主要记录项目实战过程中所遇到的Bug或因后果及提供真实有效的解决方案&#xff0c;希望能够助你一臂之力&#xff0c;帮你早日登顶实现财富自由&#x1f680;&#xff1b;同时&#xff0c;欢迎大家关注&&am…

IDEA里面的长截图插件

1.我的悲惨经历 兄弟们啊&#xff0c;我太惨了&#xff0c;我刚刚在准备这个继承和多态的学习&#xff0c;写博客的时候想要截图代码&#xff0c;因为这个代码比较大&#xff0c;一张图截取不下来&#xff0c;所以需要长截图&#xff0c;之前使用的qq截图突然间拉胯&#xff0…

栈和队列相互实现(Java)

本篇任务 前篇我们分别介绍了栈和队列&#xff0c;并对其进行了简单的自我实现&#xff0c;本篇我们将通过栈和队列的相互实现来进一步熟悉和运用栈和队列&#xff0c;如下是我们将要完成的题目&#xff1a; 用队列实现栈https://leetcode-cn.com/problems/implement-stack-u…