当前位置: 首页 > 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;以下是几种常见的错误情况及其修复方法…...

应用升级/灾备测试时使用guarantee 闪回点迅速回退

1.场景 应用要升级,当升级失败时,数据库回退到升级前. 要测试系统,测试完成后,数据库要回退到测试前。 相对于RMAN恢复需要很长时间&#xff0c; 数据库闪回只需要几分钟。 2.技术实现 数据库设置 2个db_recovery参数 创建guarantee闪回点&#xff0c;不需要开启数据库闪回。…...

css实现圆环展示百分比,根据值动态展示所占比例

代码如下 <view class""><view class"circle-chart"><view v-if"!!num" class"pie-item" :style"{background: conic-gradient(var(--one-color) 0%,#E9E6F1 ${num}%),}"></view><view v-else …...

椭圆曲线密码学(ECC)

一、ECC算法概述 椭圆曲线密码学&#xff08;Elliptic Curve Cryptography&#xff09;是基于椭圆曲线数学理论的公钥密码系统&#xff0c;由Neal Koblitz和Victor Miller在1985年独立提出。相比RSA&#xff0c;ECC在相同安全强度下密钥更短&#xff08;256位ECC ≈ 3072位RSA…...

Qt/C++开发监控GB28181系统/取流协议/同时支持udp/tcp被动/tcp主动

一、前言说明 在2011版本的gb28181协议中&#xff0c;拉取视频流只要求udp方式&#xff0c;从2016开始要求新增支持tcp被动和tcp主动两种方式&#xff0c;udp理论上会丢包的&#xff0c;所以实际使用过程可能会出现画面花屏的情况&#xff0c;而tcp肯定不丢包&#xff0c;起码…...

以下是对华为 HarmonyOS NETX 5属性动画(ArkTS)文档的结构化整理,通过层级标题、表格和代码块提升可读性:

一、属性动画概述NETX 作用&#xff1a;实现组件通用属性的渐变过渡效果&#xff0c;提升用户体验。支持属性&#xff1a;width、height、backgroundColor、opacity、scale、rotate、translate等。注意事项&#xff1a; 布局类属性&#xff08;如宽高&#xff09;变化时&#…...

电脑插入多块移动硬盘后经常出现卡顿和蓝屏

当电脑在插入多块移动硬盘后频繁出现卡顿和蓝屏问题时&#xff0c;可能涉及硬件资源冲突、驱动兼容性、供电不足或系统设置等多方面原因。以下是逐步排查和解决方案&#xff1a; 1. 检查电源供电问题 问题原因&#xff1a;多块移动硬盘同时运行可能导致USB接口供电不足&#x…...

让AI看见世界:MCP协议与服务器的工作原理

让AI看见世界&#xff1a;MCP协议与服务器的工作原理 MCP&#xff08;Model Context Protocol&#xff09;是一种创新的通信协议&#xff0c;旨在让大型语言模型能够安全、高效地与外部资源进行交互。在AI技术快速发展的今天&#xff0c;MCP正成为连接AI与现实世界的重要桥梁。…...

有限自动机到正规文法转换器v1.0

1 项目简介 这是一个功能强大的有限自动机&#xff08;Finite Automaton, FA&#xff09;到正规文法&#xff08;Regular Grammar&#xff09;转换器&#xff0c;它配备了一个直观且完整的图形用户界面&#xff0c;使用户能够轻松地进行操作和观察。该程序基于编译原理中的经典…...

CSS设置元素的宽度根据其内容自动调整

width: fit-content 是 CSS 中的一个属性值&#xff0c;用于设置元素的宽度根据其内容自动调整&#xff0c;确保宽度刚好容纳内容而不会超出。 效果对比 默认情况&#xff08;width: auto&#xff09;&#xff1a; 块级元素&#xff08;如 <div>&#xff09;会占满父容器…...

安宝特方案丨船舶智造的“AR+AI+作业标准化管理解决方案”(装配)

船舶制造装配管理现状&#xff1a;装配工作依赖人工经验&#xff0c;装配工人凭借长期实践积累的操作技巧完成零部件组装。企业通常制定了装配作业指导书&#xff0c;但在实际执行中&#xff0c;工人对指导书的理解和遵循程度参差不齐。 船舶装配过程中的挑战与需求 挑战 (1…...