5、Spring_DI注解开发

news2024/10/5 18:33:56

DI 注解开发

1.目前面临问题

  • 建立 mapper

    public interface EmployeeMapper {
        void save();
    }
    
  • 建立 mapper 实现类

    @Repository
    public class EmployeeMapperImpl implements EmployeeMapper {
        public void save(){
            System.out.println("保存员工信息");
        }
    }
    
  • 建立 service

    public interface IEmployeeService {
        void save();
    }
    
  • 建立 service 实现类

    @Service
    public class EmployeeServiceImpl implements IEmployeeService {
    
        private EmployeeMapper employeeMapper;
    
        public void setEmployeeMapper(EmployeeMapper employeeMapper){
            this.employeeMapper = employeeMapper;
        }
        public void save() {
            employeeMapper.save();
        }
    }
    
  • 设置配置类

    @Configuration
    @ComponentScan("cn.sycoder.di.di01")
    public class DiConfig {
    }
    
  • 出现空指针异常

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-oSHnV3L7-1692700773739)(picture/image-20221028160214170.png)]

2.使用类型注入

  • @Autowired按照类型注入

  • 通过构造器注入

    @Autowired
    public EmployeeServiceImpl(EmployeeMapper employeeMapper) {
        this.employeeMapper = employeeMapper;
    }
    
  • 通过setter 方法注入

    @Autowired
    public void setEmployeeMapper(EmployeeMapper employeeMapper) {
        this.employeeMapper = employeeMapper;
    }
    
  • 直接在属性上使用(是以后用得最多的)

    @Service
    public class EmployeeServiceImpl implements IEmployeeService {
    
        @Autowired
        private EmployeeMapper employeeMapper;
    
        public void save() {
            employeeMapper.save();
        }
    }
    
    • 注意:不提供setter 方法以及构造器是使用反射创建对象的

      @Test
          public void autowired() throws Exception {
              final Class<?> aClass = Class.forName("cn.sycoder.di.di01.service.impl.EmployeeServiceImpl");
              final Object o = aClass.newInstance();
              final Field[] fields = aClass.getDeclaredFields();
              AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DiConfig.class);
              final EmployeeMapper bean = context.getBean(EmployeeMapper.class);
              for (Field field : fields) {
                  field.setAccessible(true);
                  field.set(o,bean);
              }
              final EmployeeServiceImpl service = (EmployeeServiceImpl) o;
              service.save();
          }
      
    • 根据类型注入必须只有一个实现类,否则会报错,添加名称也不行

      [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZJHcdvtU-1692700773741)(picture/image-20221028161616168.png)]

  • 属性required=false,如果找不到不会报错

3.使用名称注入

  • @Autowired & @Qualifier

  • @Autowired & @Qualifier必须同时使用,缺一不可

  • 解决刚才出现两个实现类没法注入的问题

  • 配置mapper 并且指定实现类的名称

    public interface EmployeeMapper {
        void save();
    }
    
    @Repository("empMapper2")
    public class EmployeeMapperImpl implements EmployeeMapper {
        public void save(){
            System.out.println("保存员工信息");
        }
    }
    
    @Repository("empMapper1")
    public class EmployeeMapperImpl1 implements EmployeeMapper{
        public void save() {
            System.out.println("save");
        }
    }
    
  • 注入的时候使用名称注入

    @Service
    public class EmployeeServiceImpl implements IEmployeeService {
    
        @Autowired(required = false)
        @Qualifier("empMapper1")
        private EmployeeMapper employeeMapper;
    
        public void save() {
            employeeMapper.save();
        }
    
    }
    

4.简单数据类型注入

  • @Value

    @Component
    public class DbProperties {
        
        @Value("sy")
        private String username;
        @Value("123456")
        private String password;
        
    }
    
  • 硬编码,太垃圾了,需要改成动态

5.注解读取配置文件参数

  • @Value

  • 修改配置类

    @Configuration
    @ComponentScan("cn.sycoder.di.di01")
    @PropertySource("db.properties")
    public class DiConfig {
    }
    
  • 修改获取方式使用 ${} 的方式

    @Component
    public class DbProperties {
    
        @Value("${username}")
        private String username;
        @Value("${password}")
        private String password;
    
        public void test(){
            System.out.println(username + ":" + password);
        }
    }
    

5.1@PropertySource

  • @PropertySource 加载配置文件

  • 位置:配置类上

  • 作用导入配置文件

  • 对于多个配置文件

    @Configuration
    @ComponentScan("cn.sycoder.di.di01")
    @PropertySource({"db.properties","xx.properties"})
    public class DiConfig {
    }
    

6.注解配置第三方bean

6.1配置 druid

  • 添加依赖

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.2.8</version>
    </dependency>
    
  • 先添加配置类 SpringConfig

    @Configuration
    public class SpringConfig {
    
    
        public DataSource dataSource(){
            final DruidDataSource source = new DruidDataSource();
            source.setUsername("root");
            source.setPassword("123456");
            source.setDriverClassName("com.mysql.cj.jdbc.Driver");
            source.setUrl("jdbc:mysql://localhost:3306/mybatis");
            return source;
        }
    
    }
    
  • 传统做法存在硬编码,DataSource 并且没有交给 spring 管理,每次都需要重新新建 DataSource ,并不存在单例一说

    @Test
        public void testDruid(){
            AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
            final SpringConfig bean = context.getBean(SpringConfig.class);
            System.out.println(bean.dataSource());
        }
    

6.2@Bean 配置 druid

  • 使用@Bean 交给 spring 管理

    @Configuration
    public class SpringConfig {
    
        @Bean
        public DataSource dataSource(){
            final DruidDataSource source = new DruidDataSource();
            source.setUsername("root");
            source.setPassword("123456");
            source.setDriverClassName("com.mysql.cj.jdbc.Driver");
            source.setUrl("jdbc:mysql://localhost:3306/mybatis");
            return source;
        }
    
    }
    
  • 修改配置的硬编码改成软编码

    @Configuration
    @PropertySource("druidDb.properties")
    public class SpringConfig {
        @Value("${jdbc.username}")
        private String username;
        @Value("${jdbc.password}")
        private String password;
        @Value("${jdbc.url}")
        private String url;
        @Value("${jdbc.driverClassName}")
        private String driver;
    
        @Bean
        public DataSource dataSource(){
            final DruidDataSource source = new DruidDataSource();
            source.setUsername(username);
            source.setPassword(password);
            source.setDriverClassName(driver);
            source.setUrl(url);
            return source;
        }
    
    }
    
    jdbc.username=root
    jdbc.password=123456
    jdbc.driverClassName=com.mysql.cj.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/mybatis
    
  • @Bean 与 xml 对应

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Xn4DyXfT-1692697345778)(picture/image-20221029105022768.png)]

7.使用@Import 实现配置导入

  • 目前存在:任何类都配置到配置类里面,不方便管理,也不方便维护

7.1配置 Component 解决

  • @Component

    @Component
    public class DruidConfig {
        @Value("{jdbc.username}")
        private String username;
        @Value("{jdbc.password}")
        private String password;
        @Value("{jdbc.url}")
        private String url;
        @Value("{jdbc.driverClassName}")
        private String driver;
    
    
        @Bean
        public DataSource dataSource(){
            final DruidDataSource source = new DruidDataSource();
            source.setUsername(username);
            source.setPassword(password);
            source.setDriverClassName(driver);
            source.setUrl(url);
            return source;
        }
    }
    

7.2使用@import

  • 修改druidConfig

    @Configuration
    public class DruidConfig {
        @Value("{jdbc.username}")
        private String username;
        @Value("{jdbc.password}")
        private String password;
        @Value("{jdbc.url}")
        private String url;
        @Value("{jdbc.driverClassName}")
        private String driver;
    
    
        @Bean
        public DataSource dataSource(){
            final DruidDataSource source = new DruidDataSource();
            source.setUsername(username);
            source.setPassword(password);
            source.setDriverClassName(driver);
            source.setUrl(url);
            return source;
        }
    }
    
  • 修改spring配置类

    @Configuration
    @PropertySource("druidDb.properties")
    @Import({DruidConfig.class})
    public class SpringConfig {
    }
    
  • 如果需要传参,只需要将参数交给spring管理就行了

    @Configuration
    public class RepositoryConfig {
         @Bean
         public AccountRepository accountRepository(DataSource dataSource) {
            return new JdbcAccountRepository(dataSource);
         }
    }
    

8.注解开发总结

注解配置xml 配置功能说明
@Component
@Controller
@Service
@Repository
bean 标签(id,class)定义bean
@ComponentScan<context:component-scan base-package=“cn.sycoder.ioc.xmlAnnotationBean”/>扫描包加载bean
@Autowired
@Qualifier
@Value
setter 注入
构造器注入
自动装配
依赖注入
@Beanbean 标签,静态工厂模式,实例工厂模式,FactoryBean配置第三方bean
@Scopebean 标签中的 scope 属性设置作用域
@PostConstructor
@PreDestroy
bean 标签中的 init-method / destroy-method生命周期相关
@Import导入其它的配置类
@PropertySource({“db.properties”,“xx.properties”})<context:property-placeholder system-properties-mode=“NEVER” location=“*.properties”/>导入配置文件

9.lombok 地址

  • lombok学习地址

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

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

相关文章

档案开发:增加查询和打卡按钮

档案开发&#xff1a;增加查询和打卡按钮 和单据开发的不同点 没有单据类型不是右击–>特性–>单据主表/单据子表&#xff0c;而是右击–>特性–>选择想要的接口访问器类型是NCVO不需要映射不是项目右键–>新建–>其他–>主子表单据结点&#xff0c;而是…

怕封店吗?来看看这份亚马逊测评宝典吧!

测评&#xff0c;一直是跨境电商亚马逊行业常谈论的话题&#xff0c;因为它是获取销量最快的方法之一&#xff0c;但对于测评&#xff0c;跨境电商亚马逊平台也是深恶痛绝&#xff0c;严厉打击测评行为&#xff0c;但不少的卖家仍旧喜欢铤而走险&#xff0c;做测评去提高店铺的…

Python打印七夕礼物

参考&#xff1a; python写七夕硬核礼物&#xff01; - 周旋机器视觉的文章 - 知乎 https://zhuanlan.zhihu.com/p/196451223 # -*- coding:utf-8 -*-# 导入opencv和openpyxl import openpyxl import cv2 as cv import numpy as np from openpyxl import load_workbook from o…

组织机构代码,注册号,纳税人识别号有什么区别?海关备案是什么?

组织机构代码&#xff0c;注册号&#xff0c;纳税人识别号有什么区别&#xff1f; 之前写过关于企业信用代码的文章&#xff0c;今天来讲一下企业的三证合一。三证合一指的是将识别号&#xff0c;注册号&#xff0c;组织机构代码三者共用一个号的说法。 但是&#xff0c;你看…

群英荟萃,决战渝城 | 第七届集创赛“加速科技杯”总决赛圆满落幕!

8月20-22日&#xff0c;第七届全国大学生集成电路创新创业大赛全国总决赛在重庆举办&#xff0c;“加速科技杯”中有26支优秀队伍从四百多支报名队伍中脱颖而出&#xff0c;获得总决赛各项大奖&#xff0c;取得了优异的成绩&#xff01;大赛同期举办的还有集创赛嘉年华、人才对…

python 项目打包器pyinstaller实践

在创建了独立应用&#xff08;自包含该应用的依赖包&#xff09;之后&#xff0c;还可以使用 PyInstaller 将 Python 程序生成可直接运行的程序&#xff0c;这个程序就可以被分发到对应的 Windows 或 Mac OS X 平台上运行。 安装 PyInstalle Python 默认并不包含 PyInstaller…

高隔音活动隔断墙是一种设计用于隔离声音、提供隐私和创建灵活空间的分隔墙

高隔音活动隔断墙是一种设计用于隔离声音、提供隐私和创建灵活空间的分隔墙。这种隔断墙通常在需要随时改变房间布局的场合&#xff0c;如酒店、会议中心、展览厅、办公室等地使用。 以下是有关高隔音活动隔断墙的一些重要特点和优势&#xff1a; 1. 隔音性能&#xff1a;高隔音…

Protobuf在IDEA中的插件安装教程

&#x1f337;&#x1f341; 博主猫头虎 带您 Go to New World.✨&#x1f341; &#x1f984; 博客首页——猫头虎的博客&#x1f390; &#x1f433;《面试题大全专栏》 文章图文并茂&#x1f995;生动形象&#x1f996;简单易学&#xff01;欢迎大家来踩踩~&#x1f33a; &a…

【中危】Apache Ivy<2.5.2 存在XXE漏洞 (CVE-2022-46751)

漏洞描述 Apache Ivy 是一个管理基于 ANT 项目依赖关系的开源工具&#xff0c;文档类型定义(DTD)是一种文档类型定义语言,它用于定义XML文档中所包含的元素以及元素之间的关系。 Apache Ivy 2.5.2之前版本中&#xff0c;当解析自身配置、Ivy 文件或 Apache Maven 的 POM 文件…

改变住宅区空气质量,你一定要知道!

在现代城市生活中&#xff0c;住宅区的环境质量对居民的健康和舒适感起着至关重要的作用。扬尘颗粒和噪声不仅直接影响人们的日常生活&#xff0c;还可能对居民的健康和生活品质造成持续的影响。 在不断提升环保意识的同时&#xff0c;政府、社区和居民也将共同努力&#xff0c…

0基础入门代码审计-2 Fortify初探

0x01 序言 目前又加入一位新童鞋了&#xff0c;最近将会再加入cs相关的专栏&#xff0c;都是以基础为主&#xff0c;毕竟太复杂的东西&#xff0c;能看懂的人太少。 0x02 准备工具 1、Fortify 2、需要审计的源码 0x03 Fortify的简单使用 1、 1、在开始菜单栏中找到Audit Wo…

【Flutter】Flutter 使用 font_awesome_flutter 展示图标

【Flutter】Flutter 使用 font_awesome_flutter 展示图标 文章目录 一、前言二、安装和基本使用1. 安装2. 基本使用示例3. 图标的命名和样式 三、自定义图标和高级功能1.动态检索图标2.排除样式和优化 四、完整示例五、总结 一、前言 在现代移动应用开发中&#xff0c;图标起着…

Dockerfile制作LAMP环境镜像

文章目录 使用Dockerfile制作LAMP环境镜像编写Dockerfile不修改默认页面修改默认页面 Start Script目录结构及文件登录私有仓库给镜像打标签上传镜像页面检查检测镜像可用性 使用Dockerfile制作LAMP环境镜像 编写Dockerfile 不修改默认页面 FROM centos:7 MAINTAINER "…

怎么把cad文件转成图片?

怎么把cad文件转成图片&#xff1f;我知道有些朋友经常需要制作各种 CAD 图纸。通常情况下&#xff0c;这些图纸以 DWG 格式保存&#xff0c;只能使用专业的 CAD 软件来打开。但是&#xff0c;如果你想与他人共享这些 CAD 图纸&#xff0c;并且对方的计算机上没有安装 CAD 软件…

实验五 Linux 内核的安装与加载

【实验目的】 掌握 uboot 的使用方法&#xff0c;能够使用 uboot 安装和加载内核 【实验环境】 ubuntu 14.04 发行版FS4412 实验平台 【注意事项】 实验步骤中以“$”开头的命令表示在 ubuntu 环境下执行&#xff0c;以“#”开头的命令表 示在开发板下执行 【实验步骤】 …

cve-2023-3079漏洞与patch分析

POC function set(arr, key, val) {arr[key] val; } function leak_hole() {for(let i 0; i < 10; i) {set(arguments, "foo", 1);}set(new Array(), 0, 1);set(arguments, 0, 1);return arguments[1]; } %DebugPrint(leak_hole());分析 通过对此漏洞的patch分…

ASEMI新能源专用整流桥GBU816参数,GBU816封装

编辑-Z GBU816参数描述&#xff1a; 型号&#xff1a;GBU816 最大峰值反向电压(VRRM)&#xff1a;1600V 平均整流正向电流(IF)&#xff1a;8A 正向浪涌电流(IFSM)&#xff1a;200A 工作接点温度和储存温度(TJ, Tstg)&#xff1a;-55 to 150℃ 最大热阻(RθJC)&#xff1…

融云深度参与「新加坡 GTLC 大会」,连接亚太机遇、开拓国际市场

8 月 18 日&#xff0c;由 TGO 鲲鹏会主办的新加坡 GTLC&#xff08;Global Tech Leadership Conference&#xff0c;全球技术领导力大会&#xff09;圆满收官&#xff0c;融云作为共创伙伴深度参与了大会。关注【融云全球互联网通信云】了解更多 本次大会以“Connecting Asia…

RunnerGo性能测试时如何从数据库获取数据

我们在做性能测试或者场景测试时往往需要从数据库中获取一些真实的系统数据让我们配置的场景更加贴合实际。而RunnerGo也是在最近的大版本更新中推出连接数据库功能&#xff0c;本篇文章也给大家讲解一下具体的操作方法和实际应用场景。 配置数据库 首先进入RunnerGo页面&…

Java实现excel表数据的批量存储(结合easyexcel插件)

场景&#xff1a;加哥最近在做项目时&#xff0c;苦于系统自身并未提供数据批量导入的功能还不能自行添加上该功能&#xff0c;且自身不想手动一条一条将数据录入系统。随后&#xff0c;自己使用JDBC连接数据库、使用EasyExcel插件读取表格并将数据按照业务逻辑批量插入数据库完…