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();}}

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

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

相关文章

Tcl lnit error: Can’t find a usable init.tcl in the following directories 问题解决

这个问题出现在我用py2exe打包了一个包含tkinter的图形化界面&#xff0c;在当前电脑上运行无问题&#xff0c;在移动到新电脑上后提示报错、 这里吐槽一下&#xff0c;新电脑上报错信息一闪而过&#xff0c;我用的土法子解决的&#xff0c;就是录视频然后0.25倍速度暂定找到报…

Acrobat 9 安装教程

软件介绍 Adobe Acrobat 是由Adobe公司开发的一款PDF&#xff08;Portable Document Format&#xff0c;便携式文档格式&#xff09;编辑软件。借助它&#xff0c;可以以PDF格式制作和保存文档&#xff0c;以便于浏览和打印&#xff0c;同时还可以使用一些高级工具来创建、编辑…

Qt 菜单栏、工具栏、状态栏、标签、铆接部件(浮动窗口) 设置窗口核心部件(文本编辑控件)的基本使用

效果 代码 #include "mainwindow.h" #include "ui_mainwindow.h" #include<QToolBar> #include<QDebug> #include<QPushButton> #include<QStatusBar> #include<QLabel> #include<QDockWidget> #include<QTextEdi…

将事物分为三教九流?不妨通过logistic回归

和多元线性回归一样&#xff0c;逻辑回归也是建立“多对一”型变量之间的线性关系——也即找出线性方程的近似解。有所不同的是&#xff0c;逻辑回归的解只能出现0~1之间&#xff08;亦或就是0/1两种结果&#xff09;&#xff0c;这倒是有点像bool型和int型之间的区别了。实际上…

S32K3 工具篇7:如何使用VScode编译EB MCAL工程

S32K3 工具篇7&#xff1a;如何使用VScode编译EB MCAL工程 1. VScode工具与配置2. 使用VScode编译RTD MCAL工程2.1 使用EB tresos生成配置2.2 VScode 打开工程2.3 修改mk文件2.4 编译文件2.5 debug生成好的elf文件 对于EB配置的MCAL代码&#xff0c;通常是基于RTD去做&#xff…

GEO IGEO MEO介绍 和 北斗导航系统使用三轨道原因

GEO IGSO MEO基本轨道知识 中地球轨道&#xff08;MEO&#xff1a;Middle Earth Orbit&#xff09; 轨道高度2000-36000kmGPS、GLONASS都属于此类轨道 地球同步轨道&#xff08;或称对地静止轨道&#xff09;[同步转动] 轨道高度约为36000 km&#xff1b;此轨道上卫星运行方…

情感识别系统源码分享

情感识别检测系统源码分享 [一条龙教学YOLOV8标注好的数据集一键训练_70全套改进创新点发刊_Web前端展示] 1.研究背景与意义 项目参考AAAI Association for the Advancement of Artificial Intelligence 项目来源AACV Association for the Advancement of Computer Vision …

发工资-python

题目要求&#xff1a; 代码&#xff1a; import random from random import randintmoney 10000 for i in range(1, 21):performance randint(1, 10)if performance < 5:print(f"员工{i},绩效分{performance},低于5,不发工资&#xff0c;下一位")continueif m…

每日学习一个数据结构-倒排表

文章目录 示意图倒排表的基本概念倒排表的数据结构示例 倒排表的优点应用场景 倒排表&#xff08;Inverted Index&#xff09;&#xff0c;也称为反向索引或倒排文件&#xff0c;在信息检索系统中是一种重要的数据结构。它主要用于快速搜索文档中的关键词&#xff0c;并找到包含…

字典+泛型的栈与队列+委托

字典 在System.Collections.Generic下&#xff0c;对应HashTable,添加了泛型的特性&#xff0c;性能更高更安全&#xff0c;在内存中散列排布&#xff0c;存储也是键值对。 Dictionary<键的数据类型&#xff0c;值的数据类型> 字典名new Dictionary<键的数据类型&am…

异常冲突行为和危险识别系统源码分享

异常冲突行为和危险识别检测系统源码分享 [一条龙教学YOLOV8标注好的数据集一键训练_70全套改进创新点发刊_Web前端展示] 1.研究背景与意义 项目参考AAAI Association for the Advancement of Artificial Intelligence 项目来源AACV Association for the Advancement of Co…

教你搭建一个wifi贴系统

大家好&#xff0c;我是鲸天科技千千&#xff0c;大家都知道我是做小程序开发的&#xff0c;平时会给大家分享一些互联网相关的创业项目&#xff0c;感兴趣的可以跟我关注一下。 搭建一个首先就是要搭建一个自己的wifi贴小程序&#xff0c;我们自己的工作就是把这个小程序推广…

CAN BUS

CAN BUS 原理 网上资料非常丰富&#xff0c;是车载系统主要BUS之一。 我们关注如下方面 can bus 是什么网络结构CAN BUS 协议ECU node实现其他 What is CAN Bus? Control Area Network (CAN) bus is a serial communication protocol that allows devices to exchange dat…

JavaScript web API part3

web API DOM 日期对象 > 得到当前系统的时间 new这个操作就是实例化 语法 const date new Date() or const date new Date(2004-11-3 08:00:00) 可以指定时间 > 可应用于通过系统时间和指定时间实现倒计时的操作 //得到当前时间const date new Date()console.lo…

HTML贪吃蛇游戏

文章目录 贪吃蛇游戏 运行效果代码 贪吃蛇游戏 贪吃蛇是一款经典的休闲益智游戏。本文将通过HTML5和JavaScript详细解析如何实现一个简易版的贪吃蛇游戏。游戏的主要逻辑包括蛇的移动、碰撞检测、食物生成等功能。以下是游戏的完整代码及注释解析。&#xff08;纯属好玩&#…

【PyQt6 应用程序】应用程序携带数据源文件一并打包

在开发好应用程序打包之后给到其他用户会发现数据文件比如封面图片不见了。 例如这样,很影响用户使用。 这里介绍一个非常简单的打包方法,不光要在打包命令的时候添加对应数据文件,在源码中也要进行一些简单的修改。 修改需要添加打包文件的地方。首先需要添加一个绝对路径…

九九乘法表-while-python

i 1 while i < 9:#j 1&#xff0c;条件为j < ij 1while j < i:print(f"{j}*{i}{i*j}\t",end)#先输出jj 1print()i 1运行结果截图&#xff1a;

超分辨率技术之插值算法

&#x1f31e;欢迎莅临我的个人主页&#x1f448;&#x1f3fb;这里是我专注于深度学习领域、用心分享知识精粹与智慧火花的独特角落&#xff01;&#x1f349; &#x1f308;如果大家喜欢文章&#xff0c;欢迎&#xff1a;关注&#x1f377;点赞&#x1f44d;&#x1f3fb;评论…

单机软件在Linux上的安装

mysql安装 5.7版本 mysql的程序在centos官方的库中是没有的&#xff0c;需要切换到淘宝的镜像&#xff0c;这个前面有教程或者配置mysql的源 yum -y install rpm rpm --import https://repo.mysql.Com/RPM-GPG-KEY-mysqL-2022 rpm -Uvh http://repo.mysql.com//mysql57-commun…

Linux基础---08软件的安装

安装方式优缺点编译安装自由定制&#xff0c;但较为繁琐rmp安装安装简单&#xff0c;但需要自己解决依赖&#xff0c;不支持定制yum安装自动解决rmp依赖&#xff0c;但不支持定制&#xff08;用的更多&#xff09; 下面就具体介绍三大安装方式&#xff1a; 一.编译安装 用Li…