Spring5学习——3Bean

Posted noti9j6s

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring5学习——3Bean相关的知识,希望对你有一定的参考价值。

1.Spring里,默认bean是单实例对象

        ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        User user1 = context.getBean("user", User.class);
        User user2 = context.getBean("user",User.class);
        System.out.println(user1.equals(user2));
        //输出true,user1 = user2

Spring配置文件bean标签里面有属性scope用于设置单实例还是多实例
(1)singleton:默认值、单实例
(2)prototype:多实例

    <!--    id:实例化对象的唯一标识;  class:类的全路径     -->
    <bean id="user" class="com.dk.entity.User" scope="prototype">
        <!--属性注入:name表示属性名称,value表示属性值-->
        <property name="name" value="LiHui"></property>
        <property name="age" value="25"></property>
    </bean>

tips:
当使用Lombok的@Data注解时,则有了@EqualsAndHashCode注解,那么就会在此类中存在equals(Object other) 和 hashCode()方法,且不会使用父类的属性。如果两个对象的属性相同,就会认为这两个对象相等,即重写了hashCode和equls方法。

2.Bean的生命周期
(1)通过构造器创建Bean实例(无参数构造)
(2)为Bean的属性设置值和对其他Bean进行引用(调用Set方法)
(3)调用Bean的初始化方法
(4)获取Bean对象
(5)容器关闭时,调用Bean的销毁方法

3.自动装配
什么是自动装配:

根据属性名称和属性类型,自动将匹配的属性值进行注入

通过xml文件

bean标签中autowire = "byName" / "byType"

通过注解方式

步骤:
(1)引入依赖:spring-aop.jar
(2)开启组件扫描:

 <!-- 控件扫描-->
   <context:component-scan base-package="demo"></context:component-scan>
<!--部分扫描-->
<context:component-scan base-package="com.dk" use-default-filters="false">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

(3)创建类,在类上面添加创建对象注解

(1)@Component:普通组件
(2)@Service:业务逻辑层或service层
(3)@Controller:web层
(4)@Repository:view层或dao层

(4)基于注解方式实现属性注入

(1)@Autowired:根据属性类型进行自动装配
(2)@Qualifier:根据属性名称进行注入(和@Autowired一起使用)
(3)@Resource:可以根据类型,也可以根据名称
(4)@Value:注入普通类型属性值

以上是关于Spring5学习——3Bean的主要内容,如果未能解决你的问题,请参考以下文章

学习Spring5必知必会~未使用spring前的麻烦

Spring5——IOC操作Bean管理(基于xml文件)

Spring5学习笔记 — “IOC操作Bean管理(基于注解)”

Spring5学习笔记 — “IOC操作Bean管理(基于注解)”

Spring5学习笔记 — “Spring AOP的概念相关术语”

Spring5学习笔记 — “Spring AOP的概念相关术语”