初学Spring之自动装配 Bean

Bean 的作用域:

1.单例模式(Spring 默认机制)

scope=“singleton”

2.原型模式:每次从容器中 get 时,都会产生一个新对象

scope="prototype"

3. request、session、application,只能在 web 开发中使用

Bean 的自动装配:

自动装配是 Spring 满足 bean 依赖的一种方式

Spring 会在上下文中自动寻找,并自动给 bean 装配属性

Spring 中有三种装配的方式:

1.在 xml 中显示配置

2.在 java 中显示配置

3.隐式的自动装配 bean

写两个类

写个 Person 类,get/set 方法,toString() 方法

package com.demo.autowired;

public class Person {
    private Cat cat;
    private Dog dog;
    private String name;

    public Cat getCat() {
        return cat;
    }

    public void setCat(Cat cat) {
        this.cat = cat;
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "cat=" + cat +
                ", dog=" + dog +
                ", name='" + name + '\'' +
                '}';
    }
}

beans.xml 文件:

ByName 自动装配:autowire="byName"

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

<?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:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
						http://www.springframework.org/schema/util
						http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <bean id="cat" class="com.demo.autowired.Cat"/>
    <bean id="dog" class="com.demo.autowired.Dog"/>

    <!-- byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的bean id -->
    <bean id="person" class="com.demo.autowired.Person" autowire="byName">
<!--        <property name="cat" ref="cat"/>-->
<!--        <property name="dog" ref="dog"/>-->
        <property name="name" value="张三"/>
    </bean>
</beans>

MyTest 类:

import com.demo.autowired.Person;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Mytest {
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Person person = context.getBean("person", Person.class);
        person.getCat().shout();
        person.getDog().shout();
    }
}

同理,ByType:会自动在容器上下文中查找和自己对象属性类型相同的 bean

(Cat、Dog 的 id 都可以省略)

<bean class="com.demo.autowired.Cat"/>
<bean class="com.demo.autowired.Dog"/>
<!-- byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean -->
<bean id="person" class="com.demo.autowired.Person" autowire="byType">
    <property name="name" value="张三"/>
</bean>

总结:

byName 需要保证所有 bean 的 id 唯一,并且这个 bean 需要和自动注入的属性的 set 方法值一致

byType 需要保证所有 bean 的 class 唯一,并且这个 bean 需要和自动注入的属性的类型一致

注解实现自动装配:

Person 类添加 @Autowired 注解(在属性上使用或者在 Set 方法上使用)

beans.xml 文件:

导入 context 约束:xmlns:context="http://www.springframework.org/schema/context"

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context.xsd

配置注解的支持:<context:annotation-config/>

<?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:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
						http://www.springframework.org/schema/util
						http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <!-- 开启注解的支持 -->
    <context:annotation-config/>

    <bean id="cat" class="com.demo.autowired.Cat"/>
    <bean id="dog" class="com.demo.autowired.Dog"/>

    <bean id="person" class="com.demo.autowired.Person">
        <property name="name" value="张三"/>
    </bean>

</beans>

如果显示定义了 Autowired 的 required 属性为 false,说明这个对象可以为 null,否则不允许为空

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

@Qualifier(value="xx") 可以指定唯一的 bean 对象注入(需和 @Autowired 搭配使用)

@Resource 和 @Autowired 的区别:

1.都是用来自动装配的,都可以放在属性字段上

2. @Autowired 通过 byType 方式实现,这个对象是必须存在的

3. @Resource 默认通过 byName 方式实现,如果找不到,则通过 byType 方式实现

如果二者都找不到,就报错

  • 6
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
回答: Spring Bean的生命周期主要指的是singleton bean,它的生命周期可以分为四个阶段:实例化、属性注入、初始化和销毁。首先,在实例化阶段,通过反射创建出Bean对象。然后,在属性注入阶段,将依赖的属性注入到Bean对象中。接下来,在初始化阶段,调用Bean的初始化方法,可以通过配置文件或注解来定义初始化方法。最后,在销毁阶段,当容器关闭或者Bean被销毁时,调用Bean的销毁方法。需要注意的是,对于prototype的Bean,Spring在创建好交给使用者之后不再管理后续的生命周期。对于初学者来说,理解Spring Bean的生命周期可能会比较困难,因为涉及到的源代码比较复杂。建议初学者可以跟着教程一步一步学习,不要一开始就看复杂的源码,以免产生困惑。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [一文读懂 Spring Bean 的生命周期](https://blog.csdn.net/riemann_/article/details/118500805)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* [SpringBean的生命周期](https://blog.csdn.net/weixin_71786285/article/details/128274251)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值