spring 学习 (注解)

目录

前言

常用的注解

须知

1 @Conponent注解

demo(案例)

2 @Controller+@Service+@Repository

demo(案例)

3 @Scope+@Lazy+@PostConstruct+@PreDestroy

demo(案例)

4 @Value+@Autowired+@Qualifier+@Resource

demo(案例)

5 @Configuration+@ComponentScan+@PropertySource+@import

demo(实例)


前言

之前学习 spring 框架时,我们知道实例化bean 都是依靠 spring 配置文件,在配置文件中书写一个个bean 标签,表示将要创建的对象。

本篇博客则是 使用注解的方式,平替之前使用 spring 配置文件创建对象,等操作。

Spring的注解可以代替xml配置;通俗点来讲,注解是对xml配置的平替;原先xml配置所实现的功能,现在可以使用注解实现;而且使用注解比xml配置更符合我们编码习惯,也更简单。

常用的注解

须知

以下任何demo(案例的前提)

即使我们使用各自注解代替 标签,属性啥的。但如何去解析 注解这是我们需要思考的。

以下在配置文件中写的 标签就是解析哪个包下的注解。

<?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:context="http://www.springframework.org/schema/context"xsi:schemaLocation=" http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><!--spring会去扫描fs包及其子包下所有的注解,并让其生效-->
<context:component-scan base-package="fs">
</context:component-scan>
</beans>

注意:

1 base-package 的属性值 是 你需要扫描哪个包下的注解

2 不要直接复制粘贴,看需要哪个补充哪个,否则很容易出问题。

3 当然了,这些最后同样会有相应注解替代 配置文件,扫描注解的标签。但需要注意任何注解的底层都是 以xml 配置文件的形式存在。


1 @Conponent注解

使用目的

@Conponent注解 就可以平替<bean>标签。

特别提醒:在使用spring注解的时候,要想使spring容器认识这些注解,我们需要在bean.xml文件中配置注解组件扫描,只有配置了组件扫描,spring才会去指定包下面扫描你使用了哪些注解,并让其生效。

	<!--spring会去扫描com.frank包及其子包下所有的注解,并让其生效--><context:component-scan base-package="com.frank"></context:component-scan>

demo(案例)

使用 Conponent 注解 创建 person 类

person 类,Test 测试类

package fs.exerise;import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;@Component("person")
public class Person {
}
class Test{public static void main(String[] args) {ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");Object bean = context.getBean("person");System.out.println(bean);}
}

效果展示

注意:component 注解里的值,可以理解为表示 之前在spring 配置文件 bean 标签的id 值。


2 @Controller+@Service+@Repository

我们在实际的开发过程中是按层来进行的;为了语义上面更加明确,所以衍生出来另外三个注解来代替@Conponent。他们的作用是为了在语义上更加明确。

@Controller注解:使用在Controller层的类上面

@Service注解:使用在Service层的类上面

@Repository注解:使用在Dao层的类上面


demo(案例)


3 @Scope+@Lazy+@PostConstruct+@PreDestroy

@Scope注解:平替<bean scope="">

@Lazy注解:平替<bean lazy-init="">

@PostConstruct注解:平替<bean init-method="">

@PreDestroy注解:平替<bean destroy-method="">


demo(案例)

UserController 类

package fs.controller;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
// 相当于本类 UserController 在 配置文件的 bean 标签
@Controller("user")
// scope 属性表示作用域
@Scope(value = "singleton")
public class UserController {public UserController() {System.out.println("创建UserController");}// @PostConstruct 注解表示初始化方法
@PostConstructpublic void init () {System.out.println("UserController初始化");}// @PreDestroy 注解表示销毁方法
@PreDestroypublic void destroy () {System.out.println("UserController销毁");}
}

Test 测试类

package fs.controller;import org.springframework.context.support.ClassPathXmlApplicationContext;public class test {public static void main(String[] args) {ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("spring.xml");UserController userController = (UserController) app.getBean("user");
// 关闭 spring 容器 app.close();}}

效果展示


4 @Value+@Autowired+@Qualifier+@Resource

平替bean标签注入时的标签

原先使用xml实现注入的时候使用的是<property>标签来指明注入的关系;现在我们可以通过下面的注解来替换它。

@value注解:使用在字段或者方法上面,用于注入普通数据

@Autowired注解:使用在字段或者方法上面,用于注入引用数据(默认按照byType方式进行注入)

@Qualifier注解:使用在字段或者方法上面,搭配@Autowired根据名称进行注入

@Resource注解:使用在字段或者方法上面,根据类型或者名称进行注入


demo(案例)

userController 类

package fs.controller;import fs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
// 相当于本类 UserController 在 配置文件的 bean 标签
@Controller("user")
// scope 属性表示作用域
@Scope(value = "singleton")
public class UserController {@Autowired// @Autowired 注解表示自动注入 一般适用于 成员变量
// @Qualifier 可以为 @Autowired 注解的补充,表示注入的bean的id@Qualifier("userService")private UserService userService;// @Value 注解表示注入值@Value("dj")private  String name;public void a(){System.out.println(userService+"他的名字是"+name);}public UserController() {System.out.println("创建UserController");}// @PostConstruct 注解表示初始化方法
@PostConstructpublic void init () {System.out.println("UserController初始化");}// @PreDestroy 注解表示销毁方法
@PreDestroypublic void destroy () {System.out.println("UserController销毁");}
}

疑问:@Autowired注解是根据类型进行注入的,那如果我有多个UserDao类型呢?

答:所以这个时候@Qualifier注解的作用就起来了,它的作用是当发现你使用了@Autowired注解后,却有多个相同的类型,可以通过@Qualifier注解指定其中的一个名字进行注入(按名字注入)。

看案例:

我再新建一个UserDaoImp2类,让该类也去实现UserDao接口,重新观察 UserController 类

UserDaoImp1 类
package fs.Dao.impl;import fs.Dao.UserDao;
import org.springframework.stereotype.Repository;@Repository("UserDao1")
public class UserDaoImp1 implements UserDao {
}
UserDaoImpl2 类
package fs.Dao.impl;import fs.Dao.UserDao;
import org.springframework.stereotype.Repository;@Repository("UserDao2")
public class UserDaoImpl2 implements UserDao {
}

UserController 类

发现 ,因为存在 多个 userDao 的实现类,即使使用 Autowired 注解 也不知道 选择哪一个。

因此采取办法是 使用@Qualifier注解 选择其中一个 注入 进去

注意:@Resource注解:不给参数的时候相当于@Autowired进行注入;给了参数相当于@Autowired+@Qualifier


5 @Configuration+@ComponentScan+@PropertySource+@import

@Configuration 注解: 平替bean.xml文件

@ComponentScan 注解: 平替 <context:component-scan base-package="com.frank">

@PropertySource("jdbc.properties") 注解: 平替 <context:property-placeholder location="classpath:jdbc.properties">

@Import(MyDataSource.class)注解:平替 <import resource="classpath:">

注意:

bean.xml文件都被配置类给替换了,那么我在写测试类创建容器对象的时候就不能用

new ClassPathXmlApplicationContext(“bean.xml”)了;而是选择使用new AnnotationConfigApplicationContext(SpringConfig.class)。


demo(实例)

person 类

package fs.exerise;import org.springframework.stereotype.Component;@Component("person")
public class Person {
}

扫描所写注解的类

package fs.exerise;import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
// @Configuration 注解表示当前类是一个配置类,用来代替xml配置文件
@Configuration
// @ComponentScan 注解表示扫描包,用来代替xml配置文件
// basePackages 属性表示扫描的包
@ComponentScan(basePackages ="fs.exerise")
public class SpringConfigration {
}

Test 测试类

package fs.exerise;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class test {public static void main(String[] args) {AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfigration.class);Object bean = context.getBean("person");System.out.println(bean);}
}

效果展示

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

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

相关文章

【设计模式】【行为型模式】迭代器模式(Iterator)

&#x1f44b;hi&#xff0c;我不是一名外包公司的员工&#xff0c;也不会偷吃茶水间的零食&#xff0c;我的梦想是能写高端CRUD &#x1f525; 2025本人正在沉淀中… 博客更新速度 &#x1f44d; 欢迎点赞、收藏、关注&#xff0c;跟上我的更新节奏 &#x1f3b5; 当你的天空突…

C语言-------结构体(1)

数据类型 &#xff08;1&#xff09;基本数据类型 整型 浮点型 字符型 &#xff08;2&#xff09;构造类型 数组 结构体 结构体: 用来处理&#xff0c;现实生活中&#xff0c;更复杂的数据的描述 用来 描述复杂数据的 一种用户自定义的数…

【centos7】安装redis

rpm链接&#xff1a;http://rpms.famillecollet.com/enterprise/remi-release-7.rpm 下载remi源 wget http://rpms.famillecollet.com/enterprise/remi-release-7.rpm 安装remi源 rpm -ivh remi-release-7.rpm 查找remi源中redis的版本 yum --enablereporemi list redis …

获取整十分钟时间戳的多种方法详解

在数据处理、定时任务等场景中&#xff0c;经常需要获取当前时间的整十分钟时间戳。本文将介绍两种常用方法&#xff0c;并拓展其他实现思路&#xff0c;帮助你灵活应对不同需求。 方法一&#xff1a;datetime模块计算法 原理&#xff1a;通过截断分钟数实现时间对齐。 代码实…

AcWing 798. 差分矩阵

题目来源&#xff1a; 找不到页面 - AcWing 题目内容&#xff1a; 输入一个 n 行 m 列的整数矩阵&#xff0c;再输入 q 个操作&#xff0c;每个操作包含五个整数 x1,y1,x2,y2,c&#xff0c;其中 (x1,y1) 和 (x2,y2)表示一个子矩阵的左上角坐标和右下角坐标。 每个操作都要将…

【Python爬虫①】专栏开篇:夯实Python基础

【Python爬虫】专栏简介&#xff1a;本专栏是 Python 爬虫领域的集大成之作&#xff0c;共 100 章节。从 Python 基础语法、爬虫入门知识讲起&#xff0c;深入探讨反爬虫、多线程、分布式等进阶技术。以大量实例为支撑&#xff0c;覆盖网页、图片、音频等各类数据爬取&#xff…

数仓:核心概念,数仓系统(ETL,数仓分层,数仓建模),数仓建模方法(星型模型,雪花模型,星座模型)和步骤

数仓建模的核心概念 事实表&#xff08;Fact Table&#xff09;&#xff1a; 存储业务过程的度量值&#xff08;如销售额、订单数量等&#xff09;。 通常包含外键&#xff0c;用于关联维度表。 维度表&#xff08;Dimension Table&#xff09;&#xff1a; 存储描述性信息&…

【靶机渗透实战】AI:WEB:1

靶机下载官网AI: Web: 1 ~ VulnHub 靶机描述 Difficulty: IntermediateNetwork: DHCP (Automatically assign)Network Mode: NATThis box is designed to test skills of penetration tester. The goal is simple. Get flag from /root/flag.txt. Enumerate the box, get low…

MATLAB中contains函数用法

目录 语法 说明 示例 查找文本 使用模式进行搜索 匹配列表中的任何文本 忽略大小写 确定字符向量中是否包含子字符串 contains函数的功能是确定字符串中是否有模式。 语法 TF contains(str,pat) TF contains(str,pat,IgnoreCase,true) 说明 如果 str 包含指定的模…

【limit 1000000,10 加载很慢该怎么优化?】

在 SQL 数据库中,使用 LIMIT 子句进行分页查询时,如果偏移量(offset)很大,查询性能可能会变得非常差。 这是因为数据库需要扫描和跳过大量的记录才能到达所需的起始位置,然后再取出所需的记录数。 例如,LIMIT 1000000, 10 表示跳过前 100 万条记录,然后取接下来的 10…

Python基于 Flask 创建简单Web服务并接收文件

在全部网口上创建web服务, 监听8080端口关闭debug模式GET时返回HTML界面, 用于提交文件POST到 /upload 时, 从接收的 file 变量中读取文件, 并传递给 opencv 解析为 image 对象 from flask import Flask, request, redirect, url_for import os import cv2 import numpy impor…

zookeeper的zkCli.sh登录server报错【无法正常使用】

如果zookeeper使用zkCli.sh登录的时候老是频闪&#xff0c;没有办法正常使用&#xff0c;大概率是与java的版本不兼容 [zookeeperPostgreSQL bin]$ ./zkCli.sh Connecting to localhost:2181 2025-02-05 19:23:53,933 [myid:] - INFO [main:Environment100] - Client envir…

初始JavaEE篇 —— Spring Web MVC入门(下)

找往期文章包括但不限于本期文章中不懂的知识点&#xff1a; 个人主页&#xff1a;我要学编程程(ಥ_ಥ)-CSDN博客 所属专栏&#xff1a;JavaEE 初始JavaEE篇 —— Spring Web MVC入门&#xff08;上&#xff09; 在上篇文章中&#xff0c;我们学习了一些注解的使用、Postman模…

【verilog】函数clogb2的解读

最近经常看到clogb2函数。 源代码如下所示。 function integer clogb2; input [31:0] value; reg [31:0] tmp; reg [31:0] rt; begin tmp value - 1; for (rt 0; tmp > 0; rt rt 1) tmp tmp >> 1; clogb2 rt; end endfunction 这个函数的意思是&#xff1a;这段…

鸿蒙app开发中 tab 切换的时候 里面的子组件如何在页面出现的时候 就请求数据

解决方案 使用 鸿蒙提供的 onVisibleAreaChange 就是页面一出现就请求这个回调 .onVisibleAreaChange([0.0, 1.0], (isVisible: boolean, currentRatio: number) > {console.info(Test Text isVisible: isVisible , currentRatio: currentRatio)if (isVisible &am…

c/c++蓝桥杯经典编程题100道(19)质因数分解

汉诺塔问题 ->返回c/c蓝桥杯经典编程题100道-目录 目录 汉诺塔问题 一、题型解释 二、例题问题描述 三、C语言实现 解法1&#xff1a;递归法&#xff08;难度★&#xff09; 解法2&#xff1a;迭代法&#xff08;难度★★★&#xff09; 四、C实现 解法1&#xff1…

Linux:线程的互斥与同步

一、买票的线程安全 大部分情况&#xff0c;线程使用的数据都是局部变量&#xff0c;变量的地址空间在线程栈空间内&#xff0c;这种情况&#xff0c;变量归属单个线程&#xff0c;其他线程无法获得这种变量。 但有时候&#xff0c;很多变量都需要在线程间共享&#xff0c;这样…

ESP学习-1(MicroPython VSCode开发环境搭建)

下载ESP8266固件&#xff1a;https://micropython.org/download/ESP8266_GENERIC/win电脑&#xff1a;pip install esptools python.exe -m pip install --upgrade pip esptooo.py --port COM5 erase_flash //清除之前的固件 esptool --port COM5 --baud 115200 write_fla…

什么是多光谱环形光源

多光谱环形光源是一种用于机器视觉、工业检测和科学研究的光源设备&#xff0c;能够提供多种波长的光&#xff0c;适用于不同材料和表面的检测需求。以下是其关键特点和应用&#xff1a; 关键特点 多光谱输出&#xff1a;可发射多种波长的光&#xff08;如可见光、红外光、紫外…

什么是UV环形光源

UV环形光源是一种用于特定照明需求的设备&#xff0c;以下是其关键点&#xff1a; 定义 UV环形光源&#xff1a;发出紫外光的环形照明装置&#xff0c;常用于机器视觉、工业检测等领域。特点 均匀照明&#xff1a;环形设计确保光线均匀分布&#xff0c;减少阴影。 高亮度&…