分层解耦-05.IOCDI-DI详解

news2024/10/10 12:16:04

一.依赖注入的注解

在我们的项目中,EmpService的实现类有两个,分别是EmpServiceA和EmpServiceB。这两个实现类都加上@Service注解。我们运行程序,就会报错。

这是因为我们依赖注入的注解@Autowired默认是按照类型来寻找bean对象的进行依赖注入的,controller程序会在IOC容器中寻找到两个service的bean对象,此时他会不知道使用哪一个,就会上面的报错。 

@Autowired      // DI:依赖注入,service依赖于dao,运行时IOC容器会提供该类型的bean对象,并赋值给该变量
    private EmpService empService;

为了解决这个问题,要么就将其中的一个@Service注解去掉,或者采用方法二,使用依赖注入的注解来指定注解的优先级。

二.@Primary注解

@Primary注解作用在bean对象上,当IOC容器中有多个不同实现类的bean对象时,哪个实现类上面加上了@Primary注解,哪个实现类的bean对象就会起作用。

package com.gjw.service.impl;

import com.gjw.dao.EmpDao;
import com.gjw.pojo.Emp;
import com.gjw.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.List;

//@Component  // IOC:控制反转,将实现类对象交给容器。将当前类交给IOC容器管理,成为IOC容器中的bean
@Primary
@Service
public class EmpServiceA implements EmpService {
    @Autowired  // DI:依赖注入,service依赖于dao,运行时IOC容器会提供该类型的bean对象,并赋值给该变量
    private EmpDao empDao;
    @Override
    public List<Emp> listEmp() {
        List<Emp> empList = empDao.listEmp();
        empList.stream().forEach(emp ->
        {
            if ("1".equals(emp.getGender())) {
                emp.setGender("男");
            } else if ("2".equals(emp.getGender())) {
                emp.setGender("女");
            }
            if ("1".equals(emp.getJob())) {
                emp.setJob("讲师");
            } else if ("2".equals(emp.getJob())) {
                emp.setJob("班主任");
            } else if ("3".equals(emp.getJob())) {
                emp.setJob("就业指导");
            }
        });
        return empList;
    }
}

 

三.@Qualifier注解

@Qualifier注解主要是配合着@Autowired注解使用,在要注入的类(此处是controller)的@Autowired注解下面加上@Qualifier(bean对象名字)

(bean对象名字)默认是实现类类名首字母小写

package com.gjw.controller;
/*
    对xml文件进行处理,从而加载处理要响应的数据
 */
import com.gjw.pojo.Emp;
import com.gjw.pojo.Result;
import com.gjw.service.EmpService;
import com.gjw.service.impl.EmpServiceA;
import com.gjw.utils.XmlParserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;


@RestController
public class EmpController {
    @Autowired      // DI:依赖注入,service依赖于dao,运行时IOC容器会提供该类型的bean对象,并赋值给该变量
    @Qualifier("empServiceB")
    private EmpService empService;
    @RequestMapping("/listEmp")
    public Result list(){

        List<Emp> empList = empService.listEmp();
        return Result.success(empList);
    }
/*
    @RequestMapping("/listEmp")
    public Result list(){
        // 1.加载emp.xml,并解析emp.xml中的数据
        String file = this.getClass().getClassLoader().getResource("emp.xml").getFile();
        System.out.println(file);
        List<Emp> empList = XmlParserUtils.parse(file, Emp.class);

        // 2.对员工信息中的gender,job字段进行处理
        empList.stream().forEach(emp ->
                {
                    if ("1".equals(emp.getGender())) {
                        emp.setGender("男");
                    } else if ("2".equals(emp.getGender())) {
                        emp.setGender("女");
                    }
                    if ("1".equals(emp.getJob())) {
                        emp.setJob("讲师");
                    } else if ("2".equals(emp.getJob())) {
                        emp.setJob("班主任");
                    } else if ("3".equals(emp.getJob())) {
                        emp.setJob("就业指导");
                    }
                });
        // 3.组装数据并返回
        return Result.success(empList);
    }
*/
}

指定empServiceB这个bean对象生效。 

四.@Resouce注解 

使用@Resouce注解,@Autowired注解默认是按照bean对象的类型进行选择的。@Resouce注解是按照名称进行bean对象的选择的。@Resouce(bean对象名字)

package com.gjw.controller;
/*
    对xml文件进行处理,从而加载处理要响应的数据
 */
import com.gjw.pojo.Emp;
import com.gjw.pojo.Result;
import com.gjw.service.EmpService;
import com.gjw.service.impl.EmpServiceA;
import com.gjw.utils.XmlParserUtils;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;


@RestController
public class EmpController {
    /*@Autowired      // DI:依赖注入,service依赖于dao,运行时IOC容器会提供该类型的bean对象,并赋值给该变量
    @Qualifier("empServiceB")*/
    @Resource(name = "empServiceB")
    private EmpService empService;
    @RequestMapping("/listEmp")
    public Result list(){

        List<Emp> empList = empService.listEmp();
        return Result.success(empList);
    }
/*
    @RequestMapping("/listEmp")
    public Result list(){
        // 1.加载emp.xml,并解析emp.xml中的数据
        String file = this.getClass().getClassLoader().getResource("emp.xml").getFile();
        System.out.println(file);
        List<Emp> empList = XmlParserUtils.parse(file, Emp.class);

        // 2.对员工信息中的gender,job字段进行处理
        empList.stream().forEach(emp ->
                {
                    if ("1".equals(emp.getGender())) {
                        emp.setGender("男");
                    } else if ("2".equals(emp.getGender())) {
                        emp.setGender("女");
                    }
                    if ("1".equals(emp.getJob())) {
                        emp.setJob("讲师");
                    } else if ("2".equals(emp.getJob())) {
                        emp.setJob("班主任");
                    } else if ("3".equals(emp.getJob())) {
                        emp.setJob("就业指导");
                    }
                });
        // 3.组装数据并返回
        return Result.success(empList);
    }
*/
}

注意:当我们使用Resouce注解时,是JDK框架提供Resouce注解。而使用Autowired时使用的是springboot框架提供Autowired注解。

 五.总结

 

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

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

相关文章

基于Qt的速度仪表盘控件实现

本文将详细讲解一个基于Qt的速度仪表盘控件的实现过程&#xff0c;并对代码进行详细的注释说明。该控件可以模拟汽车仪表盘的外观&#xff0c;并通过滑动条动态改变速度显示。本文将从代码结构、绘制组件到实现细节进行讲解&#xff0c;帮助您理解如何使用Qt框架自定义绘制控件…

CSRF | GET 型 CSRF 漏洞攻击

关注这个漏洞的其他相关笔记&#xff1a;CSRF 漏洞 - 学习手册-CSDN博客 0x01&#xff1a;GET 型 CSRF 漏洞攻击 —— 理论篇 GET 型 CSRF 漏洞是指攻击者通过构造恶意的 HTTP GET 请求&#xff0c;利用用户的登录状态&#xff0c;在用户不知情的情况下&#xff0c;诱使浏览器…

Cortex-M3/M4/M7 芯片 Fault 分析原理与实战

目录 一、简介1、异常类型2、异常优先级3、同步异步问题4、异常具体类型 二、Fault exception registers1、Control registers1.1 CCR1.2 SHP1.3 SHCSR 2、Status and address registers2.1 HardFault Status Register——HSFR2.2 Configurable Fault Status Register——CFSR2…

《Linux从小白到高手》进阶实操篇:用户及权限有关的实际工作场景应用

List item 本篇为《Linux从小白到高手》进阶实操篇的第一篇&#xff0c;主要介绍分享一些用户及权限有关的实际工作场景应用。 场景1&#xff1a; 实际工作中你一定会碰到如下图所示的情景&#xff1a;本部门有5个组&#xff0c;分别为&#xff1a;①Root组&#xff1a;用户…

Python中对象obj类型确定最pythonic的方式——isinstance()函数

python中确定对象obj的类型&#xff0c;isinstance函数最是优雅&#xff0c;type、issubclass等函数也可以&#xff0c;但终究“曲折”。 (笔记模板由python脚本于2024年10月07日 19:42:38创建&#xff0c;本篇笔记适合喜欢python的coder翻阅) 【学习的细节是欢悦的历程】 Pyth…

Vue2电商项目(七)、订单与支付

文章目录 一、交易业务Trade1. 获取用户地址2. 获取订单信息 二、提交订单三、支付1. 获取支付信息2. 支付页面--ElementUI(1) 引入Element UI(2) 弹框支付的业务逻辑(这个逻辑其实没那么全)(3) 支付逻辑知识点小总结 四、个人中心1. 搭建二级路由2. 展示动态数据(1). 接口(2).…

【Kubernetes】常见面试题汇总(六十)

目录 131. pod 一直处于 pending 状态&#xff1f; 132. helm 安装组件失败&#xff1f; 特别说明&#xff1a; 题目 1-68 属于【Kubernetes】的常规概念题&#xff0c;即 “ 汇总&#xff08;一&#xff09;~&#xff08;二十二&#xff09;” 。 题目 69-113 属于…

企业经营异常怎么解除

经营异常是怎么回事&#xff1f;是什么意思&#xff1f;了解异常原因&#xff1a;我们到所属工商营业执照异常的具体原因。原因可能包括未按时提交年报、未履行即时信息公示义务、公示信息隐瞒真实情况或弄xu作jia、失联等。纠正违规行为&#xff1a;查到了异常原因&#xff0c…

洛谷P5723、P5728、P1428、P1319 Python解析

P5723 完整代码 def is_prime(y):if y < 2:return Falsefor i in range(2, int(y**0.5) 1):if y % i 0:return Falsereturn Truen int(input()) sum_primes 0 x 0if n < 2:print("0") elif n 2:print("2\n1") else:for i in range(2, n 1):i…

计数原理与组合 - 离散数学系列(三)

目录 1. 计数原理的基本概念 加法原理&#xff08;Rule of Sum&#xff09; 乘法原理&#xff08;Rule of Product&#xff09; 2. 排列与组合 排列&#xff08;Permutation&#xff09; 组合&#xff08;Combination&#xff09; 日常生活中的例子 3. 二项式定理 4. 实…

Mysql锁机制解读(敲详细)

目录 锁的概念 全局锁 表级锁 表锁 元数据锁 意向锁 锁的概念 全局锁 表级锁 表锁 元数据锁 主要是对未提交事务&#xff0c;修改表结构造成表结构混乱&#xff0c;进行控制。 在不涉及表结构变化的情况下,元素锁可以忽略。 意向锁 避免有行级锁影响加表级锁&#xff0…

Mysql(六) --- 聚合函数,分组和联合查询

文章目录 前言1.聚合函数1.1.常用的函数1.2.COUNT()1.3.SUM()1.4.AVG()1.5.MIN()、MAX() 2.GROUP BY 分组查询2.1.语法2.2.示例2.3.HAVING 子句 3.联合查询3.1.为什么要进行联合查询3.2.那么是如何进行联合查询的3.3.示例&#xff1a;一个完整的联合查询的过程3.4.内连接3.5.外…

Error:WPF项目中使用oxyplot,错误提示命名空间中不存在“Plot”名称

在OxyPlot中&#xff0c;<oxy:PlotView>和<oxy:Plot>都是用来显示图表的控件&#xff0c;在WPF项目中使用oxyplot之前&#xff0c;先通过NuGet安装依赖包&#xff1a;OxyPlot.Wpf。 <oxy:PlotView>和<oxy:Plot>使用示例&#xff1a; <oxy:PlotVie…

【算法】双指针(续)

一、盛最多水的容器 11. 盛最多水的容器 - 力扣&#xff08;LeetCode&#xff09; 给定一个长度为 n 的整数数组 height 。有 n 条垂线&#xff0c;第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。 找出其中的两条线&#xff0c;使得它们与 x 轴共同构成的容器可以容纳最多…

OJ在线评测系统 微服务 OpenFeign调整后端下 nacos注册中心配置 不给前端调用的代码 全局引入负载均衡器

OpenFeign内部调用二 4.修改各业务服务的调用代码为feignClient 开启nacos注册 把Client变成bean 该服务仅内部调用&#xff0c;不是给前端的 将某个服务标记为“内部调用”的目的主要有以下几个方面&#xff1a; 安全性: 内部API通常不对外部用户公开&#xff0c;这样可以防止…

Nginx05-基础配置案例

零、文章目录 Nginx05-基础配置案例 1、案例需求 &#xff08;1&#xff09;有如下访问 http://192.168.119.161:8081/server1/location1 访问的是&#xff1a;index_sr1_location1.htmlhttp://192.168.119.161:8081/server1/location2 访问的是&#xff1a;index_sr1_loca…

慢接口分析与优化总结

文章目录 1. 慢接口优化的意义2. 接口耗时构成3. 优化技巧3.1. 内部代码逻辑异步执行[异步思想]并行优化拒绝阻塞等待预分配与循环使用[池化思想]线程池合理设计锁粒度避免过粗优化程序结构 3.2. 缓存恰当引入缓存[空间换时间思想]缓存延迟优化提前初始化缓存[预取思想] 3.3. 数…

工具函数(截取文本第一个字为图片)

const subStringToImage (params) > {const { str ,color #FFF,background #4F54FF,size 60,fontSize 20 } paramsif(str.length < 0) return console.error(字符不能为空!)const text str.slice(0, 1)const canvas document.createElement(canvas)const ctx …

github 国内文件加速下载

参看;https://www.cnblogs.com/ting1/p/18356265 在源网址前加上 https://hub.gitmirror.com/ 或https://mirror.ghproxy.com/&#xff0c;例如&#xff1a; https://hub.gitmirror.com/https://github.com/t1m0thyj/WinDynamicDesktop/releases/download/v5.4.1/WinDynamicD…

算法题总结(十)——二叉树上

#二叉树的递归遍历 // 前序遍历递归LC144_二叉树的前序遍历 class Solution {public List<Integer> preorderTraversal(TreeNode root) {List<Integer> result new ArrayList<Integer>(); //也可以把result 作为全局变量&#xff0c;只需要一个函数即可。…