spring基本使用

文章目录

  • 1. ioc(Inversion of Control) | DI(Dependency Injection)
    • (1) maven坐标导包
    • (2) 编写配置文件bean.xml
    • (3) 配置bean
    • (4) 配置文件注入属性
  • 2. DI(dependency injection) 依赖注入(setter)其他属性
    • (1) 对象属性注入
    • (2) 数组属性输入
    • (3) 集合属性注入
    • (4) map集合注入
    • (5) 构造器注入
    • (6) 自动装配
  • 3. 注解定义bean和依赖注入
    • (1) 开启注解扫描功能(配置文件)
    • (2) 声明bean和注入属性
    • (3) 获取bean
    • (4) 注解注入
    • (5) 配置类代替配置文件
    • (6) 第三方bean配置
  • 4. AOP(Aspect Oriented Programming)面向切面编程
    • (1) 依赖导入
    • (2) 编写切面类
    • (3) 开启对aop的支持和注解扫描
    • (4) 编写测试类测试
    • (5) 插入点表达式
    • (6) 通知方法
      • 前置通知Before
      • 后置通知(AfterReturning)
      • 环绕通知(Around)
      • 异常后通知(AfterThrowing)
      • 最终通知(AfterAdvice)

1. ioc(Inversion of Control) | DI(Dependency Injection)

(1) maven坐标导包

  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.3.22</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

(2) 编写配置文件bean.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 http://www.springframework.org/schema/beans/spring-beans.xsd">
       
</beans>

(3) 配置bean

在bean.xml配置文件的中配置bean

<bean id="stu" class="com.xjy.pojo.student">
</bean>

获取注入的对象:

    @Test
    public void test1(){
        ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        student stu = context.getBean(student.class);
        stu.setName("小明");
        stu.setAge(18);
        stu.setGender('男');
        System.out.println(stu);
    }

(4) 配置文件注入属性

 <bean id="stu" class="com.xjy.pojo.student">
        <property name="name" value="小慧慧"></property>
        <property name="age" value="18"></property>
        <property name="gender" value=""></property>
    </bean>

获取对象:

    @Test
    public void test1(){
        ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        student stu = context.getBean(student.class);
        System.out.println(stu);
    }

2. DI(dependency injection) 依赖注入(setter)其他属性

(1) 对象属性注入

    <bean id="address" class="com.xjy.pojo.Address">
        <property name="province" value="云南"></property>
        <property name="city" value="昆明"></property>
        <property name="specificPosition" value="云南大学"></property>
    </bean>
    
    <bean id="stu" class="com.xjy.pojo.student">
        <!--对象属性注入-->
        <property name="address" ref="address"></property
    </bean>

(2) 数组属性输入

    <bean id="stu" class="com.xjy.pojo.student">
        <!--对象属性注入-->
        <property name="address" ref="address"></property>
        <!--数组属性数组-->
        <property name="grades">
            <array>
                <value>90</value>
                <value>70</value>
                <value>60</value>
            </array>
        </property>
    </bean>

查看结果:
在这里插入图片描述

(3) 集合属性注入

        <!--list属性注入-->
        <property name="course">
            <list>
                <value>语文</value>
                <value>数学</value>
                <value>英语</value>
            </list>
        </property>

(4) map集合注入

        <!-- map集合注入-->
        <property name="girlfriend">
            <map>
                <entry key="小诗诗" value="温柔可爱灵力大方"></entry>
            </map>
        </property>

(5) 构造器注入

声明构造方法:

    public student(String name, int age, char gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

声明bean(构造方法的参数需要和注入参数一一对应)

    <bean id="stu" class="com.xjy.pojo.student">
        <constructor-arg name="name" value="小诗诗"></constructor-arg>
        <constructor-arg name="age" value="18"></constructor-arg>
        <constructor-arg name="gender" value=""></constructor-arg>
    </bean>

(6) 自动装配

    <bean id="address" class="com.xjy.pojo.Address">
        <property name="province" value="云南"></property>
        <property name="city" value="昆明"></property>
        <property name="specificPosition" value="安宁"></property>
     </bean>
     <!--这里配置了自动装配,会到ioc中找是否有对应类型的bean,常用还可按照名称装配(byname)-->
    <bean id="stu" class="com.xjy.pojo.student" autowire="byType">
        <!--对象属性注入-->
<!--        <property name="address" ref="address"></property>-->
  </bean>

3. 注解定义bean和依赖注入

(1) 开启注解扫描功能(配置文件)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       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
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!--开启注解扫描-->
    <context:component-scan base-package="com.xjy.pojo"></context:component-scan>
    <!--加载配置文件使用${}属性占位符引用配置文件属性-->
 <context:property-placeholder location="jdbc.properties"/>
</beans>

(2) 声明bean和注入属性

@Component("address")   // 声明bean
@PropertySource("jdbc.properties") // 配置文件读取
public class Address {
    @Value("云南")   // 注入属性(可以使用${}引用配置文件属性)
    private String province;
    @Value("昆明")
    private String city;
    @Value("安宁")
    private String specificPosition;
}

(3) 获取bean

    @Test
    public void testAddressBean(){
        ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
        Address address = (Address) ctx.getBean("address");
        System.out.println(address);
    }

(4) 注解注入

	// 可以配合@Qualifier("名称")进行指定注入
    @Autowired
    private Address address;   

查看注入是否成功:

    @Test
    public void testStudent(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        student bean = context.getBean(student.class);
        System.out.println(bean);
    }

(5) 配置类代替配置文件

编写配置类:

@Configuration		// 相当于配置文件
@ComponentScan("com.xjy.pojo")   //相当于包扫描
public class beanConfig {
    
}

通过配置文件获取:

    @Test
    public void test1(){
        ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(beanConfig.class);
        Address add = context.getBean(Address.class);
        System.out.println(add);
    }

(6) 第三方bean配置

在配置文件中配置bean:

    @Bean
    public ArrayList<String> stu(){
        return new ArrayList<>();
    }

4. AOP(Aspect Oriented Programming)面向切面编程

(1) 依赖导入

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>5.3.22</version>
    </dependency>
        <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.19</version>
    </dependency>

(2) 编写切面类

@Component      // 将该类声明为bean
@Aspect         // 声明该类为切面类
public class stuAspect {

    @After("execution(* com.xjy.pojo.student.*(..))")  // 后置通知,->切入点表达式表示插入方法
    public void getCurrent(JoinPoint joinPoint){
        Class<? extends JoinPoint> aClass = joinPoint.getClass();
        System.out.println(aClass+"执行结束");
    }
}

(3) 开启对aop的支持和注解扫描

@Configuration
@EnableAspectJAutoProxy     // 开启aop的支持
@ComponentScan({"com.xjy.pojo","com.xjy.aspect"})// 扫描注解包
public class beanConfig {
}

(4) 编写测试类测试

    @Test
    public void stuTest() throws InterruptedException {
        ApplicationContext context = new AnnotationConfigApplicationContext(beanConfig.class);
        student stu = context.getBean(student.class);
        stu.getSum();
    }

(5) 插入点表达式

execution(修饰符 返回值 方法全限定名(方法参数) 异常类型)

例如: (所有修饰符,所有返回值,com.examle.service中的所有类所有方法,所有参数)
execution(* com.example.service.*.*(..))

(6) 通知方法

前置通知Before

在目标方法执行前执行的通知。可以通过定义@Before注解的方法实现

后置通知(AfterReturning)

在目标方法成功执行后执行的通知。可以通过定义@AfterReturning注解的方法实现。

环绕通知(Around)

在目标方法执行前后都可以执行的通知,而且可以控制目标方法的执行。可以通过定义@Around注解的方法实现

@Component      // 将该类声明为bean
@Aspect         // 声明该类为切面类
public class stuAspect {
    @Pointcut("execution(* com.xjy.pojo.student.*(..))")
    public void cut(){}
    @Around("cut()")  // 前置通知,->切入点表达式表示插入方法
    public int getCurrent(ProceedingJoinPoint joinPoint) throws Throwable {
        long pre = System.currentTimeMillis();
        int result = (int) joinPoint.proceed();
        long end = System.currentTimeMillis();
        System.out.println(end-pre+"执行完毕");
        return result;
    }
}

测试运行:

    @Test
    public void stuTest() throws InterruptedException {
        ApplicationContext context = new AnnotationConfigApplicationContext(beanConfig.class);
        student stu = context.getBean(student.class);
        int sum = stu.getSum();
        System.out.println(sum);
    }

异常后通知(AfterThrowing)

在目标方法抛出异常时执行的通知。可以通过定义@AfterThrowing注解的方法实现

最终通知(AfterAdvice)

无论目标方法是否正常执行完成(包括正常返回或抛出异常),都会执行的通知。可以通过定义@After注解的方法实现。

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【一刷《剑指Offer》】面试题 9:斐波那契数列(扩展:青蛙跳台阶、矩阵覆盖)

力扣对应链接&#xff1a;LCR 126. 斐波那契数 - 力扣&#xff08;LeetCode&#xff09; 牛客对应链接&#xff1a;斐波那契数列_牛客题霸_牛客网 (nowcoder.com) 核心考点&#xff1a;空间复杂度&#xff0c;fib 理解&#xff0c;剪枝重复计算。 一、《剑指Offer》内容 二、分…

ThingsBoard处理设备上报的属性并转换为可读属性

一、前言 二、案例 1、AI生成JSON数据体 2、将json数据体直接通过遥测topic发送查看效果 3、可查看目前整个数据都在一起 ​编辑 4、配置附规则链路 5、对msg的消息值&#xff0c;进行数据的转换&#xff0c;并从新进行赋值。 6、规则链路关联关系 7、再次通过MQTT发送遥…

618大促有哪些值得买的家居好物?618五款必Buy好物

来了&#xff01;来了&#xff01;万众瞩目的618购物狂欢节即将拉开帷幕&#xff0c;我们的目标清晰而坚定&#xff0c;那就是用最实惠的价格尽情享受购物的乐趣。然而&#xff0c;面对各种纷繁复杂的促销活动和琳琅满目的商品&#xff0c;选择困难症似乎也在悄然滋生。因此&am…

【自定义渲染通道】

自定义渲染通道 2023-09-07 14:58 How to Create Masks With the Custom Depth Buffer Tips - Tricks Unreal Engine.mp4 后期材质ppm_customDepth 要加入通道的物体设置 render customdepth pass postprocessvolue 设置post process materials 为上面的ppm_customDepth 不同…

【信安评估】2024年全国职业院校技能大赛高职组“信息安全管理与评估”安徽省选拔赛赛项规程

培训、环境、资料、考证 公众号&#xff1a;Geek极安云科 网络安全群&#xff1a;624032112 网络系统管理群&#xff1a;223627079 网络建设与运维群&#xff1a;870959784 移动应用开发群&#xff1a;548238632 极安云科专注于技能提升&#xff0c;赋能 2024年广东省高校的技…

PLL深度解析第一篇——PLL的知识图谱

在硬件电路中&#xff0c;时钟就像心脏一样&#xff0c;在时钟的节拍下&#xff0c;不同的芯片、不同的电路、不同的接口都可以有序的进行工作或者通信&#xff08;类似流水线一样&#xff0c;必须有节奏的运行&#xff09;。 但是在芯片中&#xff0c;不同的模块和接口工作的频…

基于SSM的物业管理系统(含源码+sql+视频导入教程+文档+PPT)

&#x1f449;文末查看项目功能视频演示获取源码sql脚本视频导入教程视频 1 、功能描述 基于SSM的物业管理系统2拥有三种角色 管理员&#xff1a;用户管理、物业管理、房产信息管理、小区概况管理、开发商管理、收费标准管理、物业公司管理等 物业&#xff1a;住户管理、收费…

C语言求 MD5 值

MD5值常被用于验证数据的完整性&#xff0c;嵌入式开发时经常用到。md5sum命令可以求MD5码&#xff0c;下面介绍如何用C语言实现MD5功能。 一、求字符串MD5值 1、md5sum命令 $ echo -n "12345678" | md5sum //获取"12345678"字符串的md5值 结果&…

1小时学会SpringBoot3+Vue3前后端分离开发

首发于Enaium的个人博客 引言 大家可能刚学会Java和Vue之后都会想下一步是什么&#xff1f;那么就先把SpringBoot和Vue结合起来&#xff0c;做一个前后端分离的项目吧。 准备工作 首先你需要懂得Java和Vue的基础知识&#xff0c;环境这里就不多说了&#xff0c;直接开始。 …

Neo-reGeorg明文流量

Neo-reGeorg 1 同IP对&#xff0c;同一个URI&#xff0c;第一个TCP流是“GET”请求&#xff0c;随后的TCP流请求为“POST”。&#xff08;jsp\jspx\php&#xff09; 2 第一个TCP流中&#xff0c;GET只有一个会话。&#xff08;jsp\jspx\php&#xff09;&#xff0c;响应body79…

stm32HAL库-GPIO

一 什么是 GPIO: GPIO(general porpose intput output), 通用输入输出端口 . 二 我们先认识芯片控制 GPIO 输出控制。 2.1LED 硬件原理如图&#xff1a; 当电流从这根电线流通&#xff0c; LED 亮。当电流不通过这根电线&#xff0c; LED 灭。 上面 PF** &#xff0c;芯片电…

平芯微PW7014中文规格书

产品概述 PW7014 具有前端过电压和过温保护功能。 支持 3V 到 36V 的宽输入电压工作范围。 过压保护阈 值可以外部设置 4V~22V 或采用内部默认 6.1V 设置。 超快的过压保护响应速度能够确保后级电路 的安全。 集成了超低导通阻抗的 nFET 开关&#xff0c; 确保电路系统应用更好…

如何替代传统的方式,提高能源企业敏感文件传输的安全性?

能源行业是一个关键的基础设施领域&#xff0c;它涉及能源的勘探、开采、生产、转换、分配和消费。随着全球经济的发展和人口的增长&#xff0c;能源需求持续上升&#xff0c;这对能源行业的可持续发展提出了挑战。能源行业的传输场景多种多样&#xff0c;需要重点关注能源企业…

性能工具之 JMeter 自定义 Java Sampler 支持国密 SM2 算法

文章目录 一、前言二、加密接口1、什么是SM22、被测接口加密逻辑 三、准备工作四、JMeter 扩展实现步骤1&#xff1a;准备开发环境步骤2&#xff1a;了解实现方法步骤3&#xff1a;runTest 方法步骤4&#xff1a;getDefaultParameters 方法步骤5&#xff1a;setupTest 方法 五、…

3.Docker常用镜像命令和容器命令详解

文章目录 1、Docker镜像命令1.1 获取镜像1.2 查看镜像1.2.1、images命令列出镜像1.2.2、tag命令添加镜像标签1.2.3、inspect命令查看详细信息1.2.4、history命令查看镜像历史 1.3 搜索镜像1.4 删除和清理镜像1.4.1、使用标签删除镜像1.4.2、清理镜像 1.5 创建镜像1.5.1、基于已…

LANGUAGE-DRIVEN SEMANTIC SEGMENTATION

环境不易满足&#xff0c;不建议复现

Google Ads广告为Demand Gen推出生成式AI工具,可自动生成广告图片

谷歌今天宣布在Google Ads广告中为Demand Gen活动推出新的生成人工智能功能。 这些工具由谷歌人工智能提供支持&#xff0c;广告商只需几个步骤即可使用文本提示创建高质量的图片。 这些由人工智能驱动的创意功能旨在增强视觉叙事能力&#xff0c;帮助品牌在YouTube、YouTube…

lesson05:C++内存管理

1.内存分布 2.c中动态内存管理 3.operator new和operator delete函数 4.new和delete实现原理 1.内存分布 1.1常见的内存分布 1.2相关问题 答案&#xff1a;CCCAA AAADAB 我们讲以下易错的部分&#xff1a; 7.数组char2是在栈上开的空间&#xff0c;然后将"a…

主机登录输入正确的密码后也不能正常登录

尝试登录主机发现不能登录&#xff0c;执行journalctl -xe 发现报错fail to start switch root&#xff0c;初步判断是缺少文件bash文件 拷贝文件发现磁盘空间不足&#xff0c;清理日志文件 然后尝试修改密码&#xff1a; 再次尝试登录&#xff0c;发现问题解决&#xff0c;同时…

python获取文件路径

文件&#xff1a;allpath_parameter.py # 获取当前目录路径 # current_dir os.getcwd() # 获取当前目录路径 realpath00 os.path.abspath(os.path.join(os.path.dirname(os.path.split(os.path.realpath(__file__))[0]), .)) print(realpath00)# 获取当前目录的上级目录路…