news 2026/2/16 4:45:55

Spring-Bean的作用域Bean的自动装配

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Spring-Bean的作用域Bean的自动装配

bean的作用域

翻译版

英文版

重点掌握单例和原型就可以了

单例模式(Spring 默认机制)

  • 所有bean 共享一个实例化对象

<beanid="user2"class="com.cike4.pojo.User"c:name="user2"c:age="20"scope="singleton"/>

测试方法

@Testpublicvoidtest2(){ApplicationContextcontext=newClassPathXmlApplicationContext("userbeans.xml");// 这里申明了类型,就不需要强壮类型 User 类了Useruser=context.getBean("user2",User.class);Useruser2=context.getBean("user2",User.class);System.out.println(user==user2);}

bean共享同一个实例化对象,所以返回true

原型模式

每次从容器中get的时候,都会产生一个新的对象

<beanid="user2"class="com.cike4.pojo.User"c:name="user2"c:age="20"scope="prototype"/>

测试方法

@Testpublicvoidtest2(){ApplicationContextcontext=newClassPathXmlApplicationContext("userbeans.xml");// 这里申明了类型,就不需要强壮类型 User 类了Useruser=context.getBean("user2",User.class);Useruser2=context.getBean("user2",User.class);System.out.println(user.hashCode());System.out.println(user2.hashCode());System.out.println(user==user2);}

两个获取的对象不相等,hash也不一样,因为实例化不一样

其余的

request、session、application、这些只能在web开发中使用

官方解释:

https://docs.spring.io/spring-framework/docs/5.2.0.RELEASE/spring-framework-reference/core.html#beans-factory-scopes https://docs.spring.io/spring-framework/reference/core/beans/factory-scopes.html

Bean的自动装配

  • 自动装配是 Spring满足bean以来的一种方式!
  • Spring会在上下文中国自动寻找,并自动给bean装配属性

在Spring中有三种装配的方式:

  1. 在XML中显示的配置
  2. 在Java中显示配置
  3. 隐式的自动装配bean 【重要的】

测试

环境搭建:一个人有两个宠物

byName自动装配

byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应beanid

<beanid="cat"class="com.cike5.pojo.Cat"/><beanid="dog"class="com.cike5.pojo.Dog"/><!-- byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应beanid --><beanclass="com.cike5.pojo.People"id="people"autowire="byName"><propertyname="name"value="cike_y"/></bean>

byType自动装配

  • byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean
    • 弊端,类型全局为一才会自动装配
<beanclass="com.cike5.pojo.Cat"/><beanclass="com.cike5.pojo.Dog"/><!-- byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean 弊端,类型全局为一才会自动装配 --><beanclass="com.cike5.pojo.People"id="people"autowire="byType"><propertyname="name"value="cike_y"/></bean>

小结:

  • byName的时候,需要保证所有bean的id唯一,并且bean需要和自动注入的属性set方法后面的字母一致!
  • byTtype的时候,需要保证所有的bean的calss唯一,并且这个bean需要和自动注入的属性的类型一致!

官方解释:

https://docs.spring.io/spring-framework/docs/5.2.0.RELEASE/spring-framework-reference/core.html#beans-autowired-annotation https://docs.spring.io/spring-framework/reference/core/beans/annotation-config/autowired.html

使用注解实现自动装配

JDK1.5支持的注解,Spring2.5就支持注解了!

The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML.

要使用注解须知:

  1. 导入约束。context约束
  2. 配置注解的支持
<context:annotation-config/>

干净并且完整的xml配置:

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="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/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"><context:annotation-config/></beans>

官方文档:

https://docs.spring.io/spring-framework/docs/5.2.0.RELEASE/spring-framework-reference/core.html#beans-annotation-config https://docs.spring.io/spring-framework/reference/core/beans/annotation-config.html https://docs.spring.io/spring-framework/reference/core/beans/annotation-config/autowired.html
@Autowired

在类的属性上面进行注释

publicclassPeople{@AutowiredprivateCatcat;@AutowiredprivateDogdog;privateStringname;publicCatgetCat(){returncat;}publicDoggetDog(){returndog;}}
  • 不需要set方法了,因为是通过反射的原理实现的
  • 使用Autowired我们可以不用编写Set方法了,前提是你这个自动装配的属性在IoC(Spring)容器中存在且符合属性类型

测试方法

@Testpublicvoidtest(){// 创建Spring容器对象ApplicationContextcontext=newClassPathXmlApplicationContext("beans.xml");// 获取bean对象Peoplepeople=context.getBean("people",People.class);people.getCat().shout();people.getDog().shout();}

科普
@Nullable字段标记了这个注解,说明这个字段可以为null

可以这样子写,让name值为空

private@NullableStringname;

查看Autowired的注解接口,可以看见默认值是true

public@interfaceAutowired{/** * Declares whether the annotated dependency is required. * <p>Defaults to {@code true}. */booleanrequired()defaulttrue;}

也可以这样子写

publicclassPeople{// 如果显示定义了Autowired 的 required属性为false,说明这个对象可以为null,否则不允许为空@Autowired(required=false)privateCatcat;@Autowired(required=false)privateDogdog;
@Qualifier

可以进行显示定义进行自动装配

@Qualifier("dog11")privateDogdog;

beans.xml 中的容器id为dog11,可以进行对应

<?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/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"><!--开启注解的支持--><context:annotation-config/><bean id="dog11"class="com.cike5.pojo.Dog"/><bean id="cat"class="com.cike5.pojo.Cat"/><bean id="people"class="com.cike5.pojo.People"/></beans>

@Autowired和@Qualifier的区别:

  • @Autowired是通过byType的方式实现的,而且这个对象必须存在
  • @Qualifier则是通过byName的方式实现的,显式定义这个容器id
@Resource

支持隐式自动装配、也支持显示定义,相当于@Autowored和@Quailifier的结合体

publicclassPeople{// 隐式定义、自动装配@ResourceprivateCatcat;
publicclassPeople{// 显示定义指定容器id、自动装配@Resource(name="cat")privateCatcat;

小结:

@Resource和 @Autowired的区别:

  • 都是自动装配的,都可以放在属性字段上
  • @Autowired通过byType的方式实现,而且必须要求这个对象必须存在【常用】
  • @Resource 默认通过byName的方式实现,如果找不到,则会通过byType实现!如果两个都找不到的情况下,就会报错!最后也可以显示定义进行装配【常用】
  • 执行的顺序不同:@Autowired通过byType的方式实现,Resource 默认通过byName的方式实现
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/2/12 8:01:17

支持GPU加速的TensorFlow-v2.9镜像实战部署教程

支持GPU加速的TensorFlow-v2.9镜像实战部署教程 在深度学习项目开发中&#xff0c;最让人头疼的往往不是模型设计本身&#xff0c;而是环境配置——“在我机器上能跑”成了团队协作中的经典难题。更别提当你要在多块GPU上训练一个Transformer模型时&#xff0c;CUDA版本不匹配…

作者头像 李华
网站建设 2026/2/15 9:06:12

从 ABP 到 CleanDDD:关于软件长期演进的一些思考

从 ABP 到 CleanDDD&#xff1a;关于软件长期演进的一些思考 最近在项目中接触到了 CleanDDD&#xff0c;也重新审视了我们长期使用的 ABP 技术栈。 这并不是一篇“反 ABP”的文章&#xff0c;而是一次站在时间维度上的技术反思。 如果你也在维护一个已经运行多年、并且还会继续…

作者头像 李华
网站建设 2026/2/3 22:49:38

为什么选择TensorFlow 2.9镜像进行大模型训练?

为什么选择TensorFlow 2.9镜像进行大模型训练&#xff1f; 在当前AI研发加速迈向工业化和规模化的背景下&#xff0c;一个稳定、高效且可复现的开发环境&#xff0c;往往比模型结构本身更能决定项目的成败。尤其是在大模型训练场景中&#xff0c;动辄数百GB显存占用、跨多卡甚至…

作者头像 李华
网站建设 2026/2/7 21:16:29

监控TensorFlow训练任务状态:Prometheus集成方案

监控TensorFlow训练任务状态&#xff1a;Prometheus集成方案 在现代深度学习项目中&#xff0c;一次模型训练可能持续数小时甚至数天。你有没有遇到过这样的场景&#xff1a;提交任务后只能干等结果&#xff0c;偶尔查看日志发现损失值早已不再下降&#xff0c;却无法第一时间察…

作者头像 李华
网站建设 2026/2/16 3:44:47

JAVA助力:同城羽毛球馆自助预约新方案

JAVA助力&#xff1a;同城羽毛球馆自助预约新方案一、方案背景与目标在全民健身热潮下&#xff0c;羽毛球作为一项广受欢迎的体育运动&#xff0c;其场馆预约需求日益增长。传统的人工预约方式存在效率低、信息不透明、管理成本高等问题。本方案旨在利用JAVA技术&#xff0c;打…

作者头像 李华