Spring学习笔记-Bean

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匹配注入
posted @ 2021-08-11 17:28  菜鸢爱敲bug  阅读(52)  评论(1编辑  收藏  举报