javaEE高阶---Spring 更简单的读取和存储对象

news2024/9/22 7:21:35

一 : 引言

经过前面的学习,我们已经可以实现基本的 Spring 读取和存储对象的操作了,但在操作的过程中我们发现读取和存储对象并没有想象中的那么“简单”,所以接下来我们要学习更加简单的操作 Bean 对象的方法 .

二 : 存储Bean对象

2.1 使用类注解

在这里插入图片描述

在这里插入图片描述

示例代码 :
在这里插入图片描述

在这里插入图片描述

运行结果 :
在这里插入图片描述

在这里插入图片描述
接下来我们对类注解进行一一验证 :

import com.component.UserComponent;
import com.configuration.UserConfiguration;
import com.controller.UserController;
import com.respository.UserRepository;
import com.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
//启动类
public class Test {
    public static void main(String[] args) {
        //1.得到Spring上下文对象
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring-config.xml");
        //2.从Spring获取bean对象[使用注解,默认命名规则:类名首字母小写]
        UserService userService = (UserService) context.getBean("userService");
        //3.使用bean
        userService.doService();

        UserRepository userRepository = (UserRepository) context.getBean("userRepository");
        userRepository.doRepository();

        UserComponent userComponent = (UserComponent) context.getBean("userComponent");
        userComponent.doComponent();

        UserConfiguration userConfiguration = (UserConfiguration) context.getBean("userConfiguration");
        userConfiguration.doConfiguration();

        UserController userController = (UserController) context.getBean("userController");
        userController.doUserController();
    }
}

代码结构基本一致 :

在这里插入图片描述
运行结果 :

在这里插入图片描述
在这里插入图片描述

Q1 : 5大类注解的关系 ?

在这里插入图片描述

@Controller、@Service、@Repository、@Configuration 都是基于@Component,它们的作用都是将Bean存储到Spring 中 .

Q2 : Bean的命名规则 ?

在这里插入图片描述

在这里插入图片描述

查看Bean命名的源码 :

在这里插入图片描述

在这里插入图片描述

2.2 使用方法注解

2.2.1 演示

在这里插入图片描述
在这里插入图片描述

方法注解Bean命名规则 :

在这里插入图片描述

2.2.2注意事项

在这里插入图片描述

2.2.3 @Bean重命名

方法一:@Bean(name="xxxxx")
package com.bean;

import com.model.User;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;

@Controller
public class UserBean {
    @Bean(name = "computerUser")
    public User user1() {
        User user = new User();
        user.setAge(18);
        user.setName("百乔");
        return user;
    }
}
import com.model.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test2 {
    public static void main(String[] args) {
        //1.得到Spring上下文对象
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring-config.xml");
        //2.从Spring获取bean对象[使用注解,默认命名规则:类名首字母小写]
        User user = (User) context.getBean("computerUser");
        //3.使用bean
        System.out.println(user);
    }
}

在这里插入图片描述

方法二:@Bean("xxxxx")
package com.bean;

import com.model.User;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;

@Controller
public class UserBean {
    @Bean("computerUser")
    public User user1() {
        User user = new User();
        user.setAge(18);
        user.setName("百乔");
        return user;
    }
}
import com.model.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test2 {
    public static void main(String[] args) {
        //1.得到Spring上下文对象
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring-config.xml");
        //2.从Spring获取bean对象[使用注解,默认命名规则:类名首字母小写]
        User user = (User) context.getBean("computerUser");
        //3.使用bean
        System.out.println(user);
    }
}

在这里插入图片描述

方法三 : @Bean("xxxx","xxxxxx")
package com.bean;

import com.model.User;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;

@Controller
public class UserBean {
    @Bean(name = {"computerUser","blackboardUser"})
    public User user1() {
        User user = new User();
        user.setAge(18);
        user.setName("百乔");
        return user;
    }
}

import com.model.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test2 {
    public static void main(String[] args) {
        //1.得到Spring上下文对象
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring-config.xml");
        //2.从Spring获取bean对象[使用注解,默认命名规则:类名首字母小写]
        User user = (User) context.getBean("blackboardUser");
        //3.使用bean
        System.out.println(user);
    }
}

在这里插入图片描述
在这里插入图片描述

三 : 获取Bean对象(依赖注入/对象装配)

在 Spring 中实现依赖注入的常见方式有以下 3 种:

  • 属性注入(Field Injection);
  • Setter 注入(Setter Injection);
  • 构造方法注入(Constructor Injection).

3.1 属性注入

属性注入是我们最熟悉,也是日常开发中使用最多的一种注入方式.
package com.controller;

import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class UserController {
    //1.属性注入
    @Autowired // 自动装配
    private UserService userService;

    public void doUserController() {
        System.out.println("Do UserController!");
        userService.doService();
    }
}

import com.controller.UserController;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test3 {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring-config.xml");
        UserController userController = (UserController) context.getBean("userController");
        userController.doUserController();
    }
}

在这里插入图片描述

在这里插入图片描述

3.2 Setter注入

package com.controller;

import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class UserController {
    //2.Setter注入
    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public void doUserController() {
        System.out.println("Do UserController!");
        userService.doService();
    }
}

import com.controller.UserController;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test3 {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring-config.xml");
        UserController userController = (UserController) context.getBean("userController");
        userController.doUserController();
    }
}

在这里插入图片描述

在这里插入图片描述

3.3 构造方法注入

package com.controller;

import com.model.User;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class UserController {
    //3.构造方法注入
      private  UserService userService;
	  
	  @Autowired
      public UserController(UserService userService) {
          this.userService = userService;
      }

    public void doUserController() {
        System.out.println("Do UserController!");
        userService.doService();
    }
}

import com.controller.UserController;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test3 {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring-config.xml");
        UserController userController = (UserController) context.getBean("userController");
        userController.doUserController();
    }
}

在这里插入图片描述

以下是关于构造方法注入的一些注意事项 :

1.当当前类只有一个构造方法时,@Autowired可以省略;当存在多个构造方法时,@Autowired注解不能省略.

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2.可以在一个构造方法里注入多个Autowired对象,且当仅有1个构造方法时,@Autowired可以省略.

package com.controller;

import com.configuration.UserConfiguration;
import com.model.User;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class UserController {
    //3.构造方法注入
      private UserService userService;
      private UserConfiguration userConfiguration;

      @Autowired
      public UserController(UserService userService,UserConfiguration userConfiguration) {
          this.userService = userService;
          this.userConfiguration = userConfiguration;
      }

      public void doUserController() {
        System.out.println("Do UserController!");
        userService.doService();
        userConfiguration.doConfiguration();
    }
}

import com.controller.UserController;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test3 {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring-config.xml");
        UserController userController = (UserController) context.getBean("userController");
        userController.doUserController();
    }
}

在这里插入图片描述

3.答:当有多个构造方法的时候,加了@Autowired 的构造方法才会执行,并且构造方法中的参数(对象)必须要存在于Spring容器中,否则就会报错.

典型错误 :

在这里插入图片描述
构造方法注入的优点 :

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
Spring4.2之前推荐使用Setter注入方式 , 原因是其符合单一性原则 ; Spring4.2之后则推荐使用构造方法注入 . 有意思的是Spring官方在源代码中更多使用的 , 却是属性注入的方式 , 因为这种方法确实非常简单 .

3.2 @Resource

在进行类注入时,除了可以使用 @Autowired 关键字之外,我们还可以使用 @Resource 进行注入 , 示例如下 :

在这里插入图片描述

@Resource注解不能使用在构造方法实现上 .

@Resource和@Autowired的区别

在这里插入图片描述

在这里插入图片描述

先看@Resource :

package com.controller;
import com.model.User;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;

@Controller
public class SheepController {
    @Resource(name = "user1")
    private User user;

    public void doSheepController() {
        System.out.println("别看我只是一只羊");
        System.out.println(user);
    }
}

import com.controller.SheepController;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test3 {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring-config.xml");
        SheepController sheepController =
                (SheepController) context.getBean("sheepController");
        sheepController.doSheepController();
    }
}

在这里插入图片描述

解释 :
在这里插入图片描述

如果使用@Autowired , 需要配合另一个Spring的注解@qualifier .

在这里插入图片描述

还可以配合@Primary注解 :

在这里插入图片描述

在这里插入图片描述

以下是一道综合练习题 , 大家可以到我的码云(SpringBoot_Demo3)查看答案 :

在这里插入图片描述
在这里插入图片描述

本节内容结束 !

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

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

相关文章

【Hack The Box】windows练习-- Reel

HTB 学习笔记 【Hack The Box】windows练习-- Reel 🔥系列专栏:Hack The Box 🎉欢迎关注🔎点赞👍收藏⭐️留言📝 📆首发时间:🌴2022年11月17日🌴 &#x1f3…

视频清晰度优化指南

一、背景介绍 随着移动互联网的深入发展,视频消费场景逐渐变成主流,早期由于手机硬件的限制问题,导致生产出来的视频画质、清晰度存在较大的问题,用户体验不太好,当时的网络也处于4G的发展阶段,网络的限制…

【Hack The Box】windows练习-- support

HTB 学习笔记 【Hack The Box】windows练习-- support 🔥系列专栏:Hack The Box 🎉欢迎关注🔎点赞👍收藏⭐️留言📝 📆首发时间:🌴2022年11月17日🌴 &#x…

策略验证_买入口诀_双管齐下买进不怕

写在前面: 1. 本文中提到的“股票策略校验工具”的具体使用操作请查看该博文; 2. 文中知识内容来自书籍《同花顺炒股软件从入门到精通》 3. 本系列文章是用来学习技法,文中所得内容都仅仅只是作为演示功能使用 目录 解说 策略代码 结果 解…

【正点原子FPGA连载】 第一章 MPSoC简介 摘自【正点原子】DFZU2EG/4EV MPSoC 之FPGA开发指南V1.0

1)实验平台:正点原子MPSoC开发板 2)平台购买地址:https://detail.tmall.com/item.htm?id692450874670 3)全套实验源码手册视频下载地址: http://www.openedv.com/thread-340252-1-1.html 第一章 MPSoC简介…

【Loadrunner】学习loadrunner——Controller与Analysis的使用(三)

文章目录1.controller的使用1.1.创建场景的方式1.2.页面的介绍1.3.场景的设置1.2.1.设置初始化1.2.2.设置启动机制1.2.3.设置性能测试脚本的执行时间1.2.4.设置虚拟用户推出机制1.3.场景的运行1.4.场景的运行方式1.4.1.按照场景的方式运行1.4.2.按照group运行2.analysis的使用2…

[数据结构] 图---图的邻接矩阵存储方式模拟实现,包括BFS广度优先遍历和DFS深度优先遍历(上)

图的邻接矩阵存储1)邻接矩阵表示法相关概念实现基础框架Graph_matrix构造函数实现基础操作获取某一顶点的下标添加边打印邻接矩阵2)BFS广度优先遍历3)DFS深度优先遍历4)最小生成树之克鲁斯卡尔算法5)最小生成树之普里姆…

毕业设计opencv 图像识别 指纹识别 - python

文章目录0 前言1 课题背景2 效果展示3 具体实现3.1 图像对比过滤3.2 图像二值化3.3 图像侵蚀细化3.4 图像增强3.5 特征点检测4 OpenCV5 最后0 前言 🔥 这两年开始毕业设计和毕业答辩的要求和难度不断提升,传统的毕设题目缺少创新和亮点,往往…

365天深度学习训练营-第6周:好莱坞明星识别

目录 一、前言 二、我的环境 三、代码实现 四、损失函数 1. binary_crossentropy(对数损失函数) 2. categorical_crossentropy(多分类的对数损失函数) 3. sparse_categorical_crossentropy(稀疏性多分类的对数损…

关于编辑器QScintilla(Scintilla)词法分析器工作原理的分析(实现注释区分)

入门,首先看我这两篇博客:关于QScintilla库的入门大全https://biao2488890051.blog.csdn.net/article/details/126798996?spm1001.2014.3001.5502 正式开始,先来看看词法分析器和编辑器的关系: (注意:如果…

李宏毅机器学习作业6-使用GAN生成动漫人物脸

理论部分参考:​李宏毅机器学习——对抗生成网络(GAN)_iwill323的博客-CSDN博客 目录 任务和数据集 评价方法 FID AFD (Anime face detection) rate DCGAN和WGAN 代码 导包 建立数据集 显示一些图片 模型设置 生成器 判别器 权…

火山引擎:数字化时代,如何给金融业注入“内容活水”?

数字化,已经成为中国经济的一架强劲发动机。 工业和信息化部统计显示,中国数字经济规模从2012年的11万亿元增长到2021年的超45万亿元,排名世界第二,数字经济占国内生产总值比重由21.6%提升至39.8%。 数据,是数字化的…

git可视化工具-idea插件使用

上一篇文章说了git的命令行操作,是不是还沉浸在命令行在指间跳跃的兴奋中,这一篇再说一说在idea中如何使用git,会让人更兴奋了,也许你会认为这会是最好用的方式的。我想说这只是最好用的方式之一。 1.功能入口 当我们在idea里想使…

键盘输入语句和位运算

键盘输入语句键盘输入语句案例:可以从控制台接收用户信息,【姓名,年龄,薪水】进制介绍案例:输出 二,十,八,十六进制的数据位运算原码、反码、补码位运算符java 中有 7 个位运算(&…

数字工业 弹性安全丨2022 Fortinet工业互联网安全发展峰会成功举办

随着数字化转型的持续推进,工业互联网的作用和地位日益加强。而 OT 安全作为工业互联网体系不可或缺的部分,虽然受到越来越多企业的关注,但仍然面临着多方面的挑战。11月16日,一年一度的 OT 安全盛会——2022 Fortinet工业互联网安…

算法设计与分析 SCAU11091 最优自然数分解问题(优先做)

11091 最优自然数分解问题(优先做) 时间限制:1000MS 代码长度限制:10KB 提交次数:0 通过次数:0 题型: 编程题 语言: G;GCC;VC;JAVA Description 问题描述:设n是一个正整数。 (1)现在将n分解为若干个互不相同的自然…

【毕业设计】电影评论情感分析 - GRU 深度学习

文章目录0 前言1 项目介绍2 情感分类介绍3 数据集4 实现4.1 数据预处理4.2 构建网络4.3 训练模型4.4 模型评估4.5 模型预测5 最后0 前言 🔥 Hi,大家好,这里是丹成学长的毕设系列文章! 🔥 对毕设有任何疑问都可以问学…

手机拍照模糊怎么办?拍摄低像素照片如何修复清晰?

相信有很多人在用手机拍摄照片时自认为应该非常精美,拍完后却发现它模糊不清!最终遗憾地错过了精彩的瞬间,令人非常遗憾!虽然手机不是专业的摄像机,拍摄时模糊在所难免。但是我们可以在前期尽量避免拍摄的照片模糊&…

感冒了吃抗生素有用吗?

点击蓝字 |关注我们 2023年《科学世界》杂志全年订阅现已开启。 现在订阅,立享7.5折,并赠送经典科普图书《从一到无穷大》。通过文末链接,即可登录“科学世界”微店订购。抗生素,简单地说就是杀死细菌的药物。更准确地…

从源码上看,RocketMQ 5.0 跟 RocketMQ 4.x相比增加了哪几个模块

今天来介绍一下 RocketMQ 5.0 源码上的变化。 RocketMQ 5.0 是一个里程碑式的版本,经历了近 5 年的打磨,代码变更达到 60%。 首先看一下源码中模块的变化,如下图: 从图中可以看到,RocketMQ 5.0 主要增加了 4 个模块儿…