Bean作用域(Bean Scope)

<!--显式设置单例模式-->
<bean id="accountService" class="com.something.DefaultAccountService" scope="singleton"/>

  • prototype【原型模式】:每个对象都有自己的bean
<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>



request、session、application均只在web开发中使用到

Bean自动装配

  • 自动装配:Spring满足Bean依赖的一种方式
  • Spring会在上下文中自动寻找并自动给bean装配属性

Spring中的三种装配方式

  1. xml中显式的配置
  2. java中显式的配置
  3. 隐式的自动装配【重点】

测试

  • 搭建环境
    • 新的普通Maven项目
    • 编写实体类【一人有一猫一狗】
/**
* @author Iris 2021/8/11
*/
public class Cat { public void shout() {
System.out.println("Miao");
}
}
public class Dog { public void shout() {
System.out.println("Wang");
}
}
public class Human {
private Dog dog;
private Cat cat;
private String name; Setter&Getter
toString();
}

ByName自动装配实现

<!--
byName:会自动在容器上下文中查找,自己对象set方法后的值对应的bean-id
-->
<bean class="cn.iris.pojo.Human" id="human" autowire="byName">
<property name="name" value="iris"/>
</bean>

ByType自动装配实现

<!--
byName:会自动在容器上下文中查找,自己对象属性类型相同的bean
-->
<bean class="cn.iris.pojo.Human" id="human" autowire="byType">
<property name="name" value="iris"/>
</bean>

注意点

  • byName自动装配时,id需与set方法后的值相同且唯一
  • byType自动装配时,需保证属性type唯一

注解实现自动装配

注解开发不一定比xml配置更好,取决于使用者和使用情况

使用注解步骤:

  1. 导入约束
<?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"> </beans>
  1. 配置注解的支持【手动高亮
<context:annotation-config/>

@Autowired

  • Autowired默认注入为byType,当同种类型数目>1时,再根据byName匹配注入
  • 【类属性/set方法】上使用即可
  • 使用后可不写set方法,前提:自动装配的属性在IoC容器中存在且符合byName
  • require(boolean)
    • false:显式设置false说明该对象可为null;
    • true:对象不可为空
@Autowired
private Dog dog;
@Autowired
private Cat cat;

@Nullable

  • 被标记字段可为null

@Qualifier

  • 添加对象id

@Resource

  • 默认byName匹配注入

最新文章

  1. Oracle系统学习摘要
  2. nav布局 在线演示 DIVCSS5
  3. 最短路问题Dijkstra算法
  4. php不允许用户提交空表单(php空值判断)
  5. linux中patch命令 -p 选项
  6. 网页显示UIWebView(一个)
  7. jenkins 杀死衍生进程
  8. 几种在shell命令行中过滤adb logcat输出的方法
  9. maven spring mybatis配置注意点
  10. hdoj 1251 字典树||map
  11. 安徽省2016“京胜杯”程序设计大赛_F_吃在工大
  12. 基于event 实现的线程安全的优先队列(python实现)
  13. mysql 8 windows 下安装
  14. Forward团队-爬虫豆瓣top250项目-项目总结
  15. 《生命》第三集:Mammals (哺乳动物)
  16. python - psutil 系统信息模块
  17. Apple Watch 开发详解
  18. Django之静态文件配置
  19. android适配pad和部分手机底部虚拟按键+沉浸式状态栏
  20. BZOJ3834 [Poi2014]Solar Panels 【数论】

热门文章

  1. 《算法详解:C++11语言描述》已出版
  2. 中文NER的那些事儿3. SoftLexicon等词汇增强详解&amp;代码实现
  3. 从 html 实现一个 react&#127877;
  4. Elasticsearch中的Term查询和全文查询
  5. explicit 关键字 禁止隐式转换
  6. 4、git和gitlab的配置(1)
  7. 11、函数(def)
  8. POJ 3984 迷宫(BFS)
  9. 使用了gitlab管理pipeline,Jenkinsfile 中在出现克隆命令流水线执行会混乱
  10. JUnit5的Tag、Filter、Order、Lifecycle