当前位置: 首页 > news >正文

Spring4-IoC2-基于注解管理bean

目录

开启组件扫描

使用注解定义bean

@Autowired注入

场景一:属性注入

场景二:set注入

场景三:构造方法注入

场景四:形参注入

场景五:只有一个构造函数,无注解

场景六:@Autowired和@Qualifier注解联合

@Resource注入

场景一:根据name注入

场景二:name未知注入

场景三:其他情况

Spring全注解开发


从 Java 5 开始,Java 增加了对注解(Annotation)的支持,它是代码中的一种特殊标记,可以在编译、类加载和运行时被读取,执行相应的处理。开发人员可以通过注解在不改变原有代码和逻辑的情况下,在源代码中嵌入补充信息

Spring 从 2.5 版本开始提供了对注解技术的全面支持,我们可以使用注解来实现自动装配,简化 Spring 的 XML 配置

格式:@注解名称(属性值1=属性值...)

Spring 通过注解实现自动装配的步骤如下:

  1. 引入依赖
  2. 开启组件扫描
  3. 使用注解定义 Bean
  4. 依赖注入

子模块spring6-ioc-annotation

开启组件扫描

Spring 默认不使用注解装配 Bean,因此我们需要在 Spring 的 XML 配置中,通过 context:component-scan 元素开启 Spring Beans的自动扫描功能。开启此功能后,Spring 会自动从扫描指定的包(base-package 属性设置)及其子包下的所有类,如果类上使用了 @Component 注解,就将该类装配到容器中

<?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-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><!--开启组件扫描功能--><context:component-scan base-package="com.qcby"></context:component-scan>
</beans>

注意:在使用 context:component-scan 元素开启自动扫描功能前,首先需要在 XML 配置的一级标签 <beans> 中添加 context 相关的约束

情况一:最基本的扫描方式

<context:component-scan base-package="com.qcby"></context:component-scan>

情况二:指定要排除的组件

<context:component-scan base-package="com.qcby"><!-- context:exclude-filter标签:指定排除规则 --><!--type:设置排除或包含的依据type="annotation",根据注解排除,expression中设置要排除的注解的全类名type="assignable",根据类型排除,expression中设置要排除的类型的全类名--><context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/><!--<context:exclude-filter type="assignable" expression="com.qcby.controller.UserController"/>--></context:component-scan>

情况三:仅扫描指定组件

<context:component-scan base-package="com.qcby" use-default-filters="false"><!-- context:include-filter标签:指定在原有扫描规则的基础上追加的规则 --><!-- use-default-filters属性:取值false表示关闭默认扫描规则 --><!-- 此时必须设置use-default-filters="false",因为默认规则即扫描指定包下所有类 --><!-- type:设置排除或包含的依据type="annotation",根据注解排除,expression中设置要排除的注解的全类名type="assignable",根据类型排除,expression中设置要排除的类型的全类名--><context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/><!--<context:include-filter type="assignable" expression="com.qcby.controller.UserController"/>-->
</context:component-scan>

使用注解定义bean

Spring 提供了以下多个注解,这些注解可以直接标注在 Java 类上,将它们定义成 Spring Bean:

注解说明
@Component该注解用于描述 Spring 中的 Bean,它是一个泛化的概念,仅仅表示容器中的一个组件(Bean),并且可以作用在应用的任何层次,例如 Service 层、Dao 层等。 使用时只需将该注解标注在相应类上即可
@Repository该注解用于将数据访问层(Dao 层)的类标识为 Spring 中的 Bean,其功能与@Component 相同
@Service该注解通常作用在业务层(Service 层),用于将业务层的类标识为 Spring 中的 Bean,其功能与 @Component 相同
@Controller该注解通常作用在控制层(如SpringMVC 的 Controller),用于将控制层的类标识为 Spring 中的 Bean,其功能与 @Component 相同

@Autowired注入

单独使用@Autowired注解,默认根据类型装配【默认是byType】

该注解可以标注在哪里?

  • 构造方法、方法、形参、属性、注解

该注解有一个required属性,默认值是true,表示在注入的时候要求被注入的Bean必须是存在的,如果不存在则报错。如果required属性设置为false,表示注入的Bean存在或者不存在都没关系,存在的话就注入,不存在的话,也不报错

场景一:属性注入

package com.qcby.autowired.controller;import com.qcby.autowired.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;@Controller
public class UserController {//注入service//第一种方式:属性注入@Autowired //根据类型找到对应对象,完成注入private UserService userService;public void add(){System.out.println("controller...");userService.add();}
}
package com.qcby.autowired.service;public interface UserService {public void add();
}
package com.qcby.autowired.service;import com.qcby.autowired.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class UserServiceImpl implements UserService{//注入dao//第一种方式:属性注入@Autowiredprivate UserDao userDao;@Overridepublic void add() {System.out.println("service...");userDao.add();}
}
package com.qcby.autowired.dao;public interface UserDao {public void add();
}
package com.qcby.autowired.dao;import org.springframework.stereotype.Repository;@Repository
public class UserDaoImpl implements UserDao{@Overridepublic void add() {System.out.println("dao...");}
}

测试:

package com.qcby;import com.qcby.autowired.controller.UserController;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestUserController {public static void main(String[] args) {ApplicationContext context =new ClassPathXmlApplicationContext("bean.xml");UserController controller = context.getBean(UserController.class);controller.add();}
}

场景二:set注入

package com.qcby.autowired.controller;import com.qcby.autowired.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;@Controller
public class UserController {//第二种方式 set方法注入private UserService userService;@Autowiredpublic void setUserService(UserService userService) {this.userService = userService;}public void add(){System.out.println("controller...");userService.add();}
}
package com.qcby.autowired.service;import com.qcby.autowired.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class UserServiceImpl implements UserService{//第二种方式 set方法注入private UserDao userDao;@Autowiredpublic void setUserDao(UserDao userDao) {this.userDao = userDao;}@Overridepublic void add() {System.out.println("service...");userDao.add();}
}

场景三:构造方法注入

package com.qcby.autowired.controller;import com.qcby.autowired.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;@Controller
public class UserController {//第三种方式 构造方法注入private UserService userService;@Autowiredpublic UserController(UserService userService) {this.userService = userService;}public void add(){System.out.println("controller...");userService.add();}
}
package com.qcby.autowired.service;import com.qcby.autowired.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class UserServiceImpl implements UserService{//第三种方式 构造方法注入private UserDao userDao;@Autowiredpublic UserServiceImpl(UserDao userDao) {this.userDao = userDao;}@Overridepublic void add() {System.out.println("service...");userDao.add();}
}

场景四:形参注入

package com.qcby.autowired.controller;import com.qcby.autowired.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;@Controller
public class UserController {//第四种方式 形参注入private UserService userService;public UserController(@Autowired UserService userService) {this.userService = userService;}public void add(){System.out.println("controller...");userService.add();}
}
package com.qcby.autowired.service;import com.qcby.autowired.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class UserServiceImpl implements UserService{//第四种方式 形参注入private UserDao userDao;public UserServiceImpl(@Autowired UserDao userDao) {this.userDao = userDao;}@Overridepublic void add() {System.out.println("service...");userDao.add();}
}

场景五:只有一个构造函数,无注解

package com.qcby.autowired.controller;import com.qcby.autowired.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;@Controller
public class UserController {//第五种方式 只有一个有参构造,无注解private UserService userService;public UserController(UserService userService) {this.userService = userService;}public void add(){System.out.println("controller...");userService.add();}
}
package com.qcby.autowired.service;import com.qcby.autowired.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class UserServiceImpl implements UserService{//第五种方式 只有一个有参构造,无注解private UserDao userDao;public UserServiceImpl(UserDao userDao) {this.userDao = userDao;}@Overridepublic void add() {System.out.println("service...");userDao.add();}
}

场景六:@Autowired和@Qualifier注解联合

package com.qcby.autowired.dao;import org.springframework.stereotype.Repository;@Repository
public class UserRedisDaoImpl implements UserDao{@Overridepublic void add() {System.out.println("dao redis...");}
}
package com.qcby.autowired.service;import com.qcby.autowired.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;@Service
public class UserServiceImpl implements UserService{//第六种方式 @Autowired和@Qualifier注解联合,根据名称注入@Autowired@Qualifier(value = "userRedisDaoImpl")private UserDao userDao;@Overridepublic void add() {System.out.println("service...");userDao.add();}
}

@Resource注入

@Resource注解也可以完成属性注入

@Resource和@Autowired的区别:

  • @Resource注解是JDK扩展包中的,也就是说属于JDK的一部分。所以该注解是标准注解,更加具有通用性;@Autowired注解是Spring框架自己的
  • @Resource注解默认根据名称装配byName,未指定name时,使用属性名作为name。通过name找不到的话会自动启动通过类型byType装配;@Autowired注解默认根据类型装配byType,如果想根据名称装配,需要配合@Qualifier注解一起用
  • @Resource注解用在属性上、setter方法上;@Autowired注解用在属性上、setter方法上、构造方法上、构造方法参数上

场景一:根据name注入

package com.qcby.resource.controller;import com.qcby.resource.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;import javax.annotation.Resource;@Controller
public class UserController {//根据名称进行注入@Resource(name = "myUserService")private UserService userService;public void add(){System.out.println("controller...");userService.add();}
}

 

场景二:name未知注入

package com.qcby.resource.service;import com.qcby.resource.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;@Service(value = "myUserService")
public class UserServiceImpl implements UserService {//不指定名称,根据属性名称进行注入private UserDao myUserDao;@Overridepublic void add() {System.out.println("service...");myUserDao.add();}
}

 

场景三:其他情况

package com.qcby.resource.controller;import com.qcby.resource.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;import javax.annotation.Resource;@Controller
public class UserController {//根据类型配置@Resourceprivate UserService userService;public void add(){System.out.println("controller...");userService.add();}
}

Spring全注解开发

全注解开发就是不再使用spring配置文件,而是写一个配置类来代替配置文件

package com.qcby.autowired.config;import com.qcby.autowired.controller.UserController;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;@Configuration //配置类
@ComponentScan("com.qcby") //开启组件扫描
public class SpringConfig {public static void main(String[] args) {//加载配置类ApplicationContext context =new AnnotationConfigApplicationContext(SpringConfig.class);UserController controller = context.getBean(UserController.class);controller.add();}}

相关文章:

Spring4-IoC2-基于注解管理bean

目录 开启组件扫描 使用注解定义bean Autowired注入 场景一&#xff1a;属性注入 场景二&#xff1a;set注入 场景三&#xff1a;构造方法注入 场景四&#xff1a;形参注入 场景五&#xff1a;只有一个构造函数&#xff0c;无注解 场景六&#xff1a;Autowired和Quali…...

AI基础 L22 Uncertainty over Time I 时间的不确定性

Time and Uncertainty 1 Time and Uncertainty States and Observations • discrete-time models: we view the world as a series of snapshots or time slices • the time interval ∆ between slices, we assume to be the same for every interval • Xt: denotes the se…...

中小型企业网络构建

1 什么是 VLAN&#xff1f; VLAN&#xff0c;指的是虚拟局域网&#xff0c;是一种 2 层技术。可以在交换机上实现广播域的隔离。从而可以减小 数据广播风暴对交换网络的影响&#xff0c;降低了网络管理难度&#xff0c;同时可以实现网络规模的灵活扩展。 2 Trunk 链路与 Acces…...

PXE服务

一.PXE服务的功能介绍 1.无盘启动&#xff1a;PXE允许计算机在没有本地存储设备的情况下启动操作系统。这对于构建无盘工作站非常有用&#xff0c;因为计算机可以直接从网络加载操作系统和其他应用程序1。 2.远程安装操作系统&#xff1a;PXE技术可以用于远程安装操作系统&…...

Docker技术深度解析与实践应用

Docker技术深度解析与实践应用 引言 在现代软件开发与部署的浪潮中&#xff0c;Docker作为一种轻量级的容器化技术&#xff0c;凭借其高效、一致和灵活的特性&#xff0c;逐渐成为云原生应用开发和部署的基石。本文将深入探讨Docker的核心概念、技术原理、实践应用&#xff0…...

链动321模式小程序开发源码

链动31模式概述 链动31模式是一种基于技术的新型商业模式&#xff0c;它通过激励用户分享和推广&#xff0c;实现用户、企业和平台的共赢。该模式通常涉及商品展示、积分系统、分享推广和排行榜等功能&#xff0c;旨在通过用户之间的社交裂变来扩大销售和品牌影响力。如何开发这…...

java开发中间件学习记录(持续更新中~)

1 Redis 2JVM 3 java基础底层 4Mysql 5 spring 6 微服务 7.......(持续更新) One:Redis篇 1:Redis 1.穿透 1.1缓存穿透 1.1.1布隆过滤器 1.2缓存击穿 2&#xff1a;击穿 1.3&#xff1a;缓存雪崩 1.4:双写一致 1.5.持久化&#xff08;RDB,AOF&#xff09; 1.6…...

(批处理)无限弹窗cmd

代码部分 echo off echo 好了&#xff0c;可以退出了 pause>nul echo 再点就要无限弹窗了&#xff01; pause >nul echo 你还点&#xff1f; pause >nul echo 再给你最后一次机会&#xff0c;别点了&#xff0c;再点准备重启 pause >nul echo 点击任意键变身奥特曼…...

解决ubuntu 24.04 ibus出现卡死、高延迟问题

问题描述 ubuntu中使用ibus经常会出现卡死、高延迟的问题&#xff0c;网上找了一些解决方法就手动输入命令是重启。但是键盘卡死了没法输入&#xff0c;不能很有效的解决问题。 解决思路 通过一个bash脚本监测ibus进程&#xff0c;当出现进程卡死的时候自动重启。 bash代码…...

减少脏页标记技术中处理时间的方法

减少脏页标记技术中处理时间的方法 一、引言 在数据库系统中,脏页标记技术对于确保数据的一致性和持久性至关重要。然而,脏页标记过程可能会消耗一定的处理时间,影响数据库的性能。因此,寻找有效的方法来减少脏页标记技术中的处理时间具有重要意义。 二、优化数据结构 …...

828华为云征文 | 华为云Flexusx与Docker技术融合,打造个性化WizNote服务

前言 华为云Flexus X实例携手Docker技术&#xff0c;创新融合打造高效个性化WizNote服务。华为云Flexus X实例的柔性算力与Docker的容器化优势相结合&#xff0c;实现资源灵活配置与性能优化&#xff0c;助力企业轻松构建稳定、高效的云端笔记平台。828华为云企业上云节特惠来袭…...

JavaScript事件处理和常用对象

文章目录 前言一、事件处理程序 1.JavaScript 常用事件2.事件处理程序的调用二、常用对象 1.Window 对象2.String 对象3.Date 对象总结 前言 JavaScript 语言是事件驱动型的。这意味着&#xff0c;该门语言可以通过事件触发来调用某一函数或者一段代码。该文还简单介绍了Window…...

Qt基础类05-尺寸类QSize

Qt基础类05-尺寸类QSize 摘要基本信息写在前面重要成员函数举例7个QSize QSize::boundedTo(const QSize &otherSize) constQSize QSize::expandedTo(const QSize &otherSize) constbool QSize::isEmpty() constbool QSize::isNull() constbool QSize::isValid() constQ…...

Vue 2中的this指向详解

在JavaScript中&#xff0c;this的指向是许多开发者经常遇到的问题&#xff0c;尤其是在使用Vue这样的框架时。在Vue 2中&#xff0c;理解this的指向对于正确地访问组件的数据和方法至关重要。 1. this在Vue组件中的指向 在Vue组件的选项中&#xff0c;this通常指向当前组件实…...

长业务事务的离线并发问题

事务指代一组操作同时成功或同时失败&#xff0c;事务可分为两类&#xff1a; 系统事务&#xff1a;即关系数据库事务&#xff0c;一次数据库连接中由start transaction或begin开启&#xff0c;commit表示提交&#xff0c;rollback表示回滚&#xff1b;业务事务&#xff1a;完…...

黑马程序员Java笔记整理(day01)

1.windowsR进入运行&#xff0c;输入cmd 2.环境变量 3.编写java第一步 4.使用idea 5.注释 6.字面量 7.变量 8.二进制 9.数据类型 10.关键词与标识符...

VMware Tools系列一:安装VMware Tools的作用

最近笔者安装了VMware Workstation pro 17&#xff0c;同时在VMware中安装了华为的Open Euler服务器&#xff0c;由于虚拟机Open Euler经常需要与宿主机win10交换数据&#xff0c;很不方便&#xff0c;而安装VMware Workstation pro 17并没有自动安装了VMware Tools &#xff0…...

使用大语言模型(LLM)修正小段乱码(Mojibake)为正常文本

Python方案 在上一篇文章ftfy&#xff1a;修正小段乱码&#xff08;Mojibake&#xff09;为正常文本的Python库中&#xff0c;我介绍了ftfy这个库。但随着持续的开发&#xff0c;我发现它仍然有一些解决不了的转换。如下&#xff1a; >>> ftfy.fix_text(‡›‘…...

C++ 访问限定符

个人主页&#xff1a;Jason_from_China-CSDN博客 所属栏目&#xff1a;C系统性学习_Jason_from_China的博客-CSDN博客 所属栏目&#xff1a;C知识点的补充_Jason_from_China的博客-CSDN博客 概念概述 C一种实现封装的方式&#xff0c;用类将对象的属性与方法结合在一块&#xf…...

几种mfc140u.dll常见错误情况,以及mfc140u.dll文件修复的方法

如果你遇到与mfc140u.dll 文件相关的错误&#xff0c;这通常指的是该mfc140u.dll文件可能丢失、损坏或与您的应用程序不兼容。详细分析关于mfc140u.dll文件错误会对系统有什么影响&#xff0c;mfc140u.dll文件处于什么样的位置&#xff1f;以下是几种常见的错误情况及其修复方法…...

golang循环变量捕获问题​​

在 Go 语言中&#xff0c;当在循环中启动协程&#xff08;goroutine&#xff09;时&#xff0c;如果在协程闭包中直接引用循环变量&#xff0c;可能会遇到一个常见的陷阱 - ​​循环变量捕获问题​​。让我详细解释一下&#xff1a; 问题背景 看这个代码片段&#xff1a; fo…...

如何在看板中体现优先级变化

在看板中有效体现优先级变化的关键措施包括&#xff1a;采用颜色或标签标识优先级、设置任务排序规则、使用独立的优先级列或泳道、结合自动化规则同步优先级变化、建立定期的优先级审查流程。其中&#xff0c;设置任务排序规则尤其重要&#xff0c;因为它让看板视觉上直观地体…...

Razor编程中@Html的方法使用大全

文章目录 1. 基础HTML辅助方法1.1 Html.ActionLink()1.2 Html.RouteLink()1.3 Html.Display() / Html.DisplayFor()1.4 Html.Editor() / Html.EditorFor()1.5 Html.Label() / Html.LabelFor()1.6 Html.TextBox() / Html.TextBoxFor() 2. 表单相关辅助方法2.1 Html.BeginForm() …...

Golang——7、包与接口详解

包与接口详解 1、Golang包详解1.1、Golang中包的定义和介绍1.2、Golang包管理工具go mod1.3、Golang中自定义包1.4、Golang中使用第三包1.5、init函数 2、接口详解2.1、接口的定义2.2、空接口2.3、类型断言2.4、结构体值接收者和指针接收者实现接口的区别2.5、一个结构体实现多…...

十九、【用户管理与权限 - 篇一】后端基础:用户列表与角色模型的初步构建

【用户管理与权限 - 篇一】后端基础:用户列表与角色模型的初步构建 前言准备工作第一部分:回顾 Django 内置的 `User` 模型第二部分:设计并创建 `Role` 和 `UserProfile` 模型第三部分:创建 Serializers第四部分:创建 ViewSets第五部分:注册 API 路由第六部分:后端初步测…...

MySQL体系架构解析(三):MySQL目录与启动配置全解析

MySQL中的目录和文件 bin目录 在 MySQL 的安装目录下有一个特别重要的 bin 目录&#xff0c;这个目录下存放着许多可执行文件。与其他系统的可执行文件类似&#xff0c;这些可执行文件都是与服务器和客户端程序相关的。 启动MySQL服务器程序 在 UNIX 系统中&#xff0c;用…...

CppCon 2015 学习:Reactive Stream Processing in Industrial IoT using DDS and Rx

“Reactive Stream Processing in Industrial IoT using DDS and Rx” 是指在工业物联网&#xff08;IIoT&#xff09;场景中&#xff0c;结合 DDS&#xff08;Data Distribution Service&#xff09; 和 Rx&#xff08;Reactive Extensions&#xff09; 技术&#xff0c;实现 …...

【Vue】scoped+组件通信+props校验

【scoped作用及原理】 【作用】 默认写在组件中style的样式会全局生效, 因此很容易造成多个组件之间的样式冲突问题 故而可以给组件加上scoped 属性&#xff0c; 令样式只作用于当前组件的标签 作用&#xff1a;防止不同vue组件样式污染 【原理】 给组件加上scoped 属性后…...

scan_mode设计原则

scan_mode设计原则 在进行mtp controller设计时&#xff0c;基本功能设计完成后&#xff0c;需要设计scan_mode设计。 1、在进行scan_mode设计时&#xff0c;需要保证mtp处于standby模式&#xff0c;不会有擦写、编程动作。 2、只需要固定mtp datasheet说明的接口即可&#xf…...

创客匠人:如何通过创始人IP打造实现知识变现与IP变现的长效增长?

在流量红利逐渐消退的当下&#xff0c;创始人IP的价值愈发凸显。它不仅能够帮助中小企业及个人创业者突破竞争壁垒&#xff0c;还能成为企业品牌影响力的核心资产。然而&#xff0c;市场上IP孵化机构鱼龙混杂&#xff0c;如何选择一家真正具备长期价值的合作伙伴&#xff1f;创…...