news 2026/4/15 13:47:34

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/4/5 2:05:55

微信小程序的协同过滤算法的校园点餐订餐系统美食圈分享系统

目录具体实现截图项目介绍论文大纲核心代码部分展示可定制开发之亮点部门介绍结论源码获取详细视频演示 &#xff1a;文章底部获取博主联系方式&#xff01;同行可合作具体实现截图 本系统&#xff08;程序源码数据库调试部署讲解&#xff09;同时还支持Python(flask,django)、…

作者头像 李华
网站建设 2026/4/10 17:44:52

告别 “瞎看”!这部靠谱短剧,让你休闲时光更有料

解锁休闲生活新方式&#xff0c;刷剧体验全面升级在快节奏的现代生活中&#xff0c;寻找一种高效、愉悦的休闲方式已成为大众的普遍需求。近年来&#xff0c;短剧以其“短平快”、强情节的特点迅速崛起&#xff0c;成为填补碎片化时间的娱乐新宠。对于广大用户而言&#xff0c;…

作者头像 李华
网站建设 2026/4/12 22:39:05

【C# 12编程效率飞跃】:主构造函数带来的5大变革

第一章&#xff1a;C# 12主构造函数概述C# 12 引入了主构造函数&#xff08;Primary Constructors&#xff09;&#xff0c;这一特性显著简化了类和结构体的构造逻辑&#xff0c;尤其在减少样板代码和提升可读性方面表现突出。主构造函数允许开发者在类型声明的同时直接定义构造…

作者头像 李华
网站建设 2026/4/11 4:28:49

C++内核配置静态优化:99%开发者忽略的3个关键编译期优化技巧

第一章&#xff1a;C内核配置静态优化概述在现代高性能系统开发中&#xff0c;C因其接近硬件的操作能力和高效的执行性能&#xff0c;被广泛应用于操作系统、嵌入式系统及底层运行时环境的构建。为了进一步提升程序效率&#xff0c;开发者常采用内核级别的静态优化策略&#xf…

作者头像 李华