bean的生命周期和基于注解管理bean

50 阅读1分钟

具体生命周期

  • bean对象的创建(调用无参数构造)
  • 给bean对象设置相关属性
  • bean后置处理器(初始化之前
  • bean对象初始化(调用指定初始化方法)
  • bean后置处理器(初始化之后
  • bean对象创建完成了,可以使用了
  • bean对象销毁(配置指定销毁方法)
  • IoC容器关闭了

目录:

配置bean:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="user" class="life.User" scope="singleton" init-method="initMethod" destroy-method="destroyMethod">
   <property name="name" value="lucy"></property>
  </bean>
</beans>

Test类:

什么是注解?

注解是代码中的一种特殊标记,可以在编译,类加载和运行时被读取,执行相应的处理。开发人员可以通过注解,在不改变原有代码和逻辑下,在源代码中嵌入补充信息。

第一步,引入相关依赖

第二步,开启组件扫描

why?因为spring默认不使用注解装配bean,因此我们需要在spring的xml配置中,通过context:component-scan元素来开启Spring Beans的自动扫描功能。

开启此功能后,Spring会自动从扫描指定的包(base-package属性设置)及其子包下的所有类,如果类上使用了@Component注解,那么该类就会装配到容器中

第三步,使用注解定义bean

@Component(value="user")