Spring更简单的读取和存储方式

news/2024/4/19 16:42:26/文章来源:https://blog.csdn.net/qq_52463861/article/details/128930970

一、配置扫描路径

要想将对象成功的存储到Spring中,必须配置一下存储对象的扫描包路径,只有被配置的包下的所有类添加了注解才能被正确的识别并保存到Spring中。

在 配置文件spring-config.xml中添加如下配置:

<?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:content="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"><!-- 设置需要存储到spring中的 bean根目录 --><content:component-scan base-package="com.beans"></content:component-scan>
</beans>

在这里插入图片描述

二、添加注解存储Bean对象

有两种类注解:
a.类注解:
@Controller(控制器)、@Service(服务)、@Repository(仓库)、@Component(组件)、@Configuration(配置)
b.方法注解:
@Bean

2.1类注解

注意事项:
a.即使在配置文件中配置了bean扫描路径,但五大类注解不能省略。
b.即使加了五大类注解,但类没有放在spring配置的bean路径下,那么也是不能将类注入到spring中的。

2.1.1 @Controller(控制器存储)

1.使用@Controller存储Bean对象

package com.beans;import org.springframework.stereotype.Controller;@Controller//将当前对象存储到spring中public class UserController {public void sayHi(String name){System.out.println("你好," + name);}
}

2.使用之前的方式获取Bean对象:

import com.beans.UserController;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;/*** 启动类*/
public class App {public static void main(String[] args) {//1.获取spring上下文ApplicationContext context =new ClassPathXmlApplicationContext("spring-config.xml");//2.得到beanUserController userController = context.getBean(UserController.class);//3.使用beanuserController.sayHi("张三");}
}

在这里插入图片描述

2.1.2 @Service(服务存储)

1.使用@Service存储Bean对象

package com.beans;import org.springframework.stereotype.Service;@Service//将当前对象存储到spring中public class UserService {public void sayHi(String name){System.out.println("你好," + name);}
}

2.使用之前的方式获取Bean对象:

import com.beans.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;/*** 启动类*/
public class App {public static void main(String[] args) {//1.获取spring上下文ApplicationContext context =new ClassPathXmlApplicationContext("spring-config.xml");//2.得到beanUserService userService = context.getBean("userService",UserService.class);//3.使用beanuserService.sayHi("李四");}
}

在这里插入图片描述

2.1.3 @Repository(仓库存储)

1.使用@Repository存储Bean对象

package com.beans;import org.springframework.stereotype.Repository;@Repository//将当前对象存储到spring中public class UserRepository {public void sayHi(String name){System.out.println("你好," + name);}
}

2.使用之前的方式获取Bean对象:

/*** 启动类*/
public class App {public static void main(String[] args) {//1.获取spring上下文ApplicationContext context =new ClassPathXmlApplicationContext("spring-config.xml");UserRepository userRepository = context.getBean("userRepository",UserRepository.class);userRepository.sayHi("王五");}
}

在这里插入图片描述

2.1.4 @Component(组件存储)

1.使用@Component存储Bean对象

package com.beans;
import org.springframework.stereotype.Component;@Component//将当前对象存储到spring中public class UserComponent {public void sayHi(String name){System.out.println("你好," + name);}
}

2.使用之前的方式获取Bean对象:

/*** 启动类*/
public class App {public static void main(String[] args) {//1.获取spring上下文ApplicationContext context =new ClassPathXmlApplicationContext("spring-config.xml");//2.得到beanUserComponent userComponent = context.getBean("userComponent",UserComponent.class);//3.使用beanuserComponent.sayHi("世界");}
}

在这里插入图片描述

2.1.5 @Configuration(配置存储)

1.使用@Configuration存储对象

package com.beans;import org.springframework.context.annotation.Configuration;@Configuration//将当前对象存储到spring中public class UserConfiguration {public void sayHi(String name){System.out.println("你好," + name);}
}

2.使用之前的方式获取Bean对象:

import com.beans.UserComponent;
import com.beans.UserController;
import com.beans.UserRepository;
import com.beans.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;/*** 启动类*/
public class App {public static void main(String[] args) {//1.获取spring上下文ApplicationContext context =new ClassPathXmlApplicationContext("spring-config.xml");//2.得到beanUserComponent userComponent= context.getBean("userComponent",UserComponent.class);//3.使用beanuserComponent.sayHi("老刘");}
}

在这里插入图片描述

2.1.6五大类注解之间的关系

查看除了@Component外,剩余四大注解的源码,不难发现都是依靠@Component实现的;因此**@Component是其他四个注解的父类。**
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2.1.7为什么需要这么多注解

按理来说,@Component是其他四个注解的父类,那就只需要用@Component就可以了,为什么还需要其他四个注解呢?看下面解释:
这和为什么每个省/市都有⾃⼰的⻋牌号是⼀样的?⽐如陕⻄的⻋牌号就是:陕X:XXXXXX,北京的⻋牌号:京X:XXXXXX,⼀样。甚⾄⼀个省不同的县区也是不同的,⽐如⻄安就是,陕A:XXXXX,咸阳:陕B:XXXXXX,宝鸡,陕C:XXXXXX,⼀样。这样做的好处除了可以节约号码之外,更重要的作⽤是可以直观的标识⼀辆⻋的归属地。

那么为什么需要怎么多的类注解也是相同的原因,就是让程序员看到类注解之后,就能直接了解当前类的⽤途。

程序的⼯程分层,调⽤流程如下:
在这里插入图片描述

2.2 Bean的命名规则

a.通常情况下,将大驼峰的类名改为小驼峰即可获取Bean对象。
在这里插入图片描述
b.当类名的首字母和第二个字母都大写,则使用原类名进行读取。
在这里插入图片描述

2.3方法注解@Bean

注意:此方法注解必须配合五大类注解之一才能有效果。

package com.beans;import com.model.User;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;@Componentpublic class UserBeans {@Bean//将对象存储到spring中public User user1(){User user = new User();user.setId(1);user.setName("张三");user.setPassword("123");return user;}}
/*** 启动类*/
public class App {public static void main(String[] args) {//1.获取spring上下文ApplicationContext context =new ClassPathXmlApplicationContext("spring-config.xml");User user1 = context.getBean("user1",User.class);System.out.println(user1);}
}

在这里插入图片描述

2.3.1 重命名Bean

a.给当前对象起一个别名

package com.beans;import com.model.User;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;@Componentpublic class UserBeans {@Bean(name = "user1")//将对象存储到spring中public User getUser(){User user = new User();user.setId(1);user.setName("张三");user.setPassword("123");return user;}}

在这里插入图片描述
在这里插入图片描述
b.给当前对象起多个别名
在这里插入图片描述
在这里插入图片描述

当重命名之后,如果使用之前的方法名,则会报错:

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

三、获取Bean对象(对象装配)

获取Bean对象也叫对象装配,是把某对象取出来放入某个类中,也叫对象注入
有以下三种实现方法:
1.属性注⼊
2.构造⽅法注⼊
3.Setter 注⼊

3.1 属性注入

在属性上加上**@Autowired**,将Service注入到Controller类中。

UserService类:

package com.beans;import com.model.User;
import org.springframework.stereotype.Service;@Service//将当前对象存储到spring中public class UserService {/*** 根据Id获取用户* @param id* @return*/public User getUserById(int id){//伪代码User user = new User();user.setId(id);user.setName("唐僧");user.setPassword("123456");return user;}
}

UserController类:

package com.beans;import com.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;@Controller//将当前对象存储到spring中public class UserController {//1.属性注入@Autowiredprivate UserService userService;public User getUserById(Integer id){return userService.getUserById(id);}
}

获取Controller中的getUserById的方法:

/*** 启动类*/
public class App {public static void main(String[] args) {//1.获取spring上下文ApplicationContext context =new ClassPathXmlApplicationContext("spring-config.xml");UserController userController = context.getBean(UserController.class);System.out.println(userController.getUserById(10));}
}

在这里插入图片描述

3.2 构造方法注入

package com.beans;import com.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;@Controller//将当前对象存储到spring中public class UserController2 {//2.构造方法注入@Autowiredprivate UserService userService;public UserController2(UserService userService){this.userService = userService;}public User getUserById(Integer id){return userService.getUserById(id);}
}
/*** 启动类*/
public class App {public static void main(String[] args) {//1.获取spring上下文ApplicationContext context =new ClassPathXmlApplicationContext("spring-config.xml");UserController2 userController2 = context.getBean(UserController2.class);System.out.println(userController2.getUserById(12));}
}

在这里插入图片描述
注意:如果当前类中只有一个构造方法,那么不加@Autowied注解也是可以获取到User对象,但是如果有多个构造方法,那就必须加@Autowied注解。

3.3 Setter注入

package com.beans;import com.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;@Controller//将当前对象存储到spring中public class UserController3 {private UserService userService;//2. Setter注入@Autowiredpublic void setUserService(UserService userService) {this.userService = userService;}public UserController3(UserService userService){this.userService = userService;}public User getUserById(Integer id){return userService.getUserById(id);}
}
/*** 启动类*/
public class App {public static void main(String[] args) {//1.获取spring上下文ApplicationContext context =new ClassPathXmlApplicationContext("spring-config.xml");UserController3 userController3 = context.getBean(UserController3.class);System.out.println(userController3.getUserById(14));}
}

在这里插入图片描述

3.4 三种注入方式的比较(面试常问)

a.属性注入:写法最简单,也最简洁。缺点是不通用,它只适用于loC框架,非loC框架不可用,只有在使用时会出现空指针异常。
b.Setter注入:Spring 早期版本推荐的注入方式,它的通用性不如构造方法注入。
c.构造方法注入:缺点是可能存在传递多个参数来实现构造方法的初始化,会导致代码很臃肿,那么如果出现了这种情况那么开发者应该反思自己代码是否符合单一职责的设计模式了;优点是通用性更好,并且他能保证在调用对象之前,此对象一定是存在的。Spring后期版本官方推荐的注入方式。

3.5 @Resource:另一种注入关键字

package com.beans;import com.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;import javax.annotation.Resource;@Controller//将当前对象存储到spring中public class UserController4 {//@Autowired@Resource//属性注入private UserService userService;public User getUserById(Integer id){return userService.getUserById(id);}
}
/*** 启动类*/
public class App {public static void main(String[] args) {//1.获取spring上下文ApplicationContext context =new ClassPathXmlApplicationContext("spring-config.xml");UserController4 userController4 = context.getBean(UserController4.class);System.out.println(userController4.getUserById(15));}
}

在这里插入图片描述

3.5.1@Resource和@Autowired的区别

a.出身不同:
@Autowired来自Spring,而 @Resource来自于JDK。
b.使用时设置的参数不同:
@Autowired只支持required参数设置,@Resource支持更多的参数设置。如name等。
c.支持不同:
@Autowired支持属性注入、构造方法注入、Setter注入,而@Resourc只支持属性注入和Setter注入,不支持构造方法注入。

3.6同一个类型下,多个bean报错

package com.beans;import com.model.User;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;@Componentpublic class UserBeans {@Bean(name = "user1")//将对象存储到spring中public User getUser(){User user = new User();user.setId(1);user.setName("张三");user.setPassword("123");return user;}@Bean(name = "user2")//将对象存储到spring中public User getUser2(){User user = new User();user.setId(1);user.setName("李四");user.setPassword("456");return user;}}
package com.beans;import com.model.User;
import org.springframework.stereotype.Controller;import javax.annotation.Resource;@Controller
public class UserController6 {@Resourceprivate User user;public void sayHi(){System.out.println(user);}
}

在这里插入图片描述
报错的原因是, Bean 对象不是唯一的。
解决方法:
1.使用@Resource注解,设置name属性
在这里插入图片描述
2.使用@Autowired+@Qualifier注解定义
在这里插入图片描述

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

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

基于UDP/TCP实现客户端服务器的网络通信程序

目录&#xff1a;前言基于UDP实现客户端服务器的网络通信程序基于TCP实现客户端服务器的网络通信程序前言网络编程的核心是Socket API&#xff0c;它是操作系统给应用程序提供的网络编程API&#xff0c;可以认为是socket api是和传输层密切相关的。在传输层里面&#xff0c;提供…

想成为年薪30万的自动化测试工程师,你必须突破的几个状态

现阶段的软件测试行业&#xff0c;最火的词莫过于自动化&#xff0c;行业里对自动化测试人才需求量越来越大&#xff0c;薪资越来越高&#xff0c;同时对员工的要求也越来越高。软件测试入行很容易&#xff0c;但是要在这行做好并不容易&#xff0c;行业里工资高的摸不到天花板…

pyqt5:python读取二进制文件(音频PCM文件)显示波形

文章目录1.使用ffmpeg生成PCM文件1.1 用 ffprobe 查看文件信息1.2 用 ffmpeg 命令转换1.3 用ffplay 测试播放PCM文件2.python读取PCM文件显示波形2.1 函数numpy.fromfile2.2 数据类型dtype说明有个项目需要输出10-50Hz的低频信号驱动线圈&#xff0c;考虑使用音频功放硬件&…

JDK9 新特性详解,2017-09-21 正式发布

1、Java9 新特性之目录结构 包含 [jdk8](https://so.csdn.net/so/search?qjdk8&spm1001.2101.3001.7020) 及以前的 jdk 版本&#xff0c;所有目录结构以及目录含义如图&#xff1a;jdk9 之后&#xff0c;目录结构发生变化如图&#xff1a;这个新特性只要了解下就可以了&am…

ChatGPT的火爆出圈,你对它有几分了解?

文章目录1.ChatGPT是什么&#xff1f;2.ChatGPT能做什么&#xff1f;2-1.什么是自然语言模型&#xff1f;3.ChatGPT带来的评价4.了解完ChatGPT之后&#xff0c;你会有什么反思&#xff1f;4-1.为什么微软不自己研发ChatGPT&#xff1f;4-2.Elon Musk为什么退出OpenAI公司&#…

深度学习——注意力机制(笔记+代码)

1.从心理学的角度出发 人类根据随意线索&#xff08;随着意志&#xff0c;主动的&#xff0c;有意识&#xff09;和不随意线索&#xff08;无主动&#xff0c;潜意识&#xff09;选择注意点 第一眼看到红色咖啡杯比较突出和易见就是潜意识的不随意线索 随着意识想主动读书&…

谁说菜鸟不会数据分析,不用Python,不用代码也轻松搞定

作为一个菜鸟&#xff0c;你可能觉得数据分析就是做表格的&#xff0c;或者觉得搞个报表很简单。实际上&#xff0c;当前有规模的公司任何一个岗位如果没有数据分析的思维和能力&#xff0c;都会被淘汰&#xff0c;数据驱动分析是解决日常问题的重点方式。很多时候&#xff0c;…

TypeScript快速入门

TypeScript快速入门1.TypeScript介绍1.1.TypeScript为什么要为JS添加类型支持1.2.TypeScript相比JS优势2.TypeScript初体验2.1.安装编译TS的工具包2.2.编译并运行TS代码2.3.简化运行TS代码3.TypeScript常用类型3.1.类型注解3.2.常用基础类型3.3.原始类型 number/string/boolean…

MG996R舵机介绍

舵机简介舵机是一种位置&#xff08;角度&#xff09;伺服的驱动器&#xff0c;适用于那些需要角度不断变化并可以保持的控制系统。在高档遥控玩具&#xff0c;如飞机、潜艇模型&#xff0c;遥控机器人中已经得到了普遍应用。舵机主要是由外壳、电路板、驱动马达、减速器与位置…

【c语言技能树】文件

Halo&#xff0c;这里是Ppeua。平时主要更新C语言&#xff0c;C&#xff0c;数据结构算法......感兴趣就关注我吧&#xff01;你定不会失望。 &#x1f308;个人主页&#xff1a;主页链接 &#x1f308;算法专栏&#xff1a;专栏链接 我会一直往里填充内容哒&#xff01; &…

NAS系列 硬件选择

转自我的博客文章https://blognas.hwb0307.com/nas/3224&#xff0c;内容更新仅在个人博客可见。欢迎关注&#xff01; 前言 经过《NAS系列 为什么你需要一台NAS》的简单介绍&#xff0c;如果你也决定像我一样组装一台自己的NAS&#xff0c;那么就千万不要错过本文喔&#xff…

负载均衡反向代理下的webshell上传+apache漏洞

目录一、负载均衡反向代理下的webshell上传1、nginx 负载均衡2、搭建环境3、负载均衡下的 WebShell连接的难点总结难点一、需要在每一台节点的相同位置都上传相同内容的 WebShell难点二、无法预测下次的请求交给哪台机器去执行。难点三、下载文件时&#xff0c;可能会出现飘逸&…

【3】深度学习之Pytorch——如何使用张量处理表格数据集(葡萄酒数据集)

张量是PyTorch中数据的基础。神经网络将张量输入并产生张量作为输出&#xff0c;实际上&#xff0c;神经网络内部和优化期间的所有操作都是张量之间的操作&#xff0c;而神经网络中的所有参数&#xff08;例如权重和偏差&#xff09;也都是张量。 怎样获取一条数据、一段视频或…

Springboot + RabbitMq 消息队列

前言 一、RabbitMq简介 1、RabbitMq场景应用&#xff0c;RabbitMq特点 场景应用 以订单系统为例&#xff0c;用户下单之后的业务逻辑可能包括&#xff1a;生成订单、扣减库存、使用优惠券、增加积分、通知商家用户下单、发短信通知等等。在业务发展初期这些逻辑可能放在一起…

openGL学习之GLFW和GLAD的下载和编译

背景:为什么使用GLFW和GLADOPenGL环境 目前主流的桌面平台是GLFW和GLAD之前使用的GLUT和Free GLUT已经基本淘汰了&#xff0c;所以记录一下如何下载GLFW和GLAD并且编译.GLFW下载:An OpenGL library | GLFW复制到你想存放的位置,我这里就存放到C盘Libaray文件夹下了,这里是我存放…

中国区注册使用ChatGPT指南(OpenAI‘s services are not available in your country)

ChatGPT又火了&#xff0c;各大平台热搜提到手软。暴增的访问量&#xff0c;即使强如ChatGPT&#xff0c;也表示顶不住了。Openai表示服务器已满负荷&#xff0c;ChatGPT暂无法提供服务由于目前ChatGPT未在中国开放&#xff0c;所以国内目前是无法注册使用ChatGPT。但我经过一番…

『 MySQL篇 』:MySQL表的聚合与联合查询

基础篇 MySQL系列专栏(持续更新中 …)1『 MySQL篇 』&#xff1a;库操作、数据类型2『 MySQL篇 』&#xff1a;MySQL表的CURD操作3『 MySQL篇 』&#xff1a;MySQL表的相关约束4『 MySQL篇 』&#xff1a;MySQL表的聚合与联合查询目录一. 聚合查询1.1 聚合函数1.2 GROUP BY子句…

Python将字典转换为csv

大家好,我是爱编程的喵喵。双985硕士毕业,现担任全栈工程师一职,热衷于将数据思维应用到工作与生活中。从事机器学习以及相关的前后端开发工作。曾在阿里云、科大讯飞、CCF等比赛获得多次Top名次。喜欢通过博客创作的方式对所学的知识进行总结与归纳,不仅形成深入且独到的理…

MySQL篇02-三大范式,多表查询

数据入库时,由于数据设计不合理&#xff0c;会存在数据重复、更新插入异常等情况, 故数据库中表的设计遵循的设计规范&#xff1a;三大范式1.第一范式(1NF)要求数据库的每一列都是不可分割的原子数据项&#xff0c;即原子性。强调的是列的原子性&#xff0c;即数据库中每一列的…

攀升MaxBook P2电脑U盘重装系统方法教学

攀升MaxBook P2电脑U盘重装系统方法教学。攀升MaxBook P2电脑是一款性价比非常高的笔记本。有用户购买了这款电脑后&#xff0c;想要将系统进行重装。今天和大家分享一个U盘重装系统的方法&#xff0c;学会这个方法后以后就可以自己轻松去重装电脑系统了。接下来一起看看具体的…