Spring中Bean的生命周期

#准备工作
最近刚开始看韩顺平老师讲的Spring基础,感觉听起来还是感觉比较好,也就教程中的案例做了实践,接下来记录一下,Spring中Bean的生命周期。

Spring的下载地址(我使用的是3.2.4):http://repo.springsource.org/libs-release-local/org/springframework/spring/

①创建工程
首先,用IDE创建一个Java工程,在工程目录下创建lib目录,复制需要引用的jar包并添加到ClassPath,因为我用的是Intellij,可能操作上与Eclipse有些不同。
②添加项目依赖Jar包
这个版本和教程中讲的2.5.5也有差异,主要是下载来的jar包中没有一个完整的包可以引用,只有一个个分开的jar包,这就使没有接触过Spring的我有些迷茫,
因为包很多,不知道哪些需要哪些不需要,查了一下资料,说是引用spring-core-3.2.4.RELEASE和spring-beans-3.2.4.RELEASE就够了,但是经过实践,还
需要引入spring-context-3.2.4.RELEASE、spring-expression-3.2.4.RELEASE和写日志的包commons-logging-1.1.1(需要单独下载)。
结论(需要引用的Jar包):
spring-core-3.2.4.RELEASE | spring-beans-3.2.4.RELEASE | spring-context-3.2.4.RELEASE | spring-expression-3.2.4.RELEASE | commons-logging-1.1.1
③创建applicationContext.xml文件
到这一步又开始迷茫了,搜索一下找到复制过来,Intellij检查到没有使用的引用都是灰色的,所以就删除了未使用的,结果为:

<?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">

</beans>

④创建类文件
User.java

 1 package com.spring.pojo;
 2 
 3 import org.springframework.beans.BeansException;
 4 import org.springframework.beans.factory.*;
 5 import org.springframework.context.ApplicationContext;
 6 import org.springframework.context.ApplicationContextAware;
 7 
 8 public class User implements BeanNameAware, BeanFactoryAware, ApplicationContextAware, InitializingBean, DisposableBean {
 9 
10     private String name;
11     // private String gender;
12     // private Work service;
13 
14     public User() {
15         System.out.println("①Constructor -> invoked");
16     }
17 
18     public User(String name) {// , String gender, Work service) {
19         this.name = name;
20         // this.gender = gender;
21         // this.service = service;
22     }
23 
24     public String getName() {
25         return name;
26     }
27 
28     public void setName(String name) {
29         System.out.println("①setName -> invoked");
30         this.name = name;
31     }
32 
33     /**
34     public String getGender() {
35         return gender;
36     }
37 
38     public void setGender(String gender) {
39         this.gender = gender;
40     }
41 
42     public Work getService() {
43         return service;
44     }
45 
46     public void setService(Work service) {
47         this.service = service;
48     }
49      */
50 
51     /**
52      * init-method
53      */
54     public void initBean() {
55         System.out.println("①initBean -> invoked");
56     }
57 
58     public void show() {
59         System.out.println("①" + this.name); // + ":" + this.gender + "\r\n" + service.getStatus());
60     }
61 
62     @Override
63     public void setBeanName(String s) {
64         System.out.println("①" + s);
65     }
66 
67     @Override
68     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
69         System.out.println("①" + applicationContext);
70     }
71 
72     @Override
73     public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
74         System.out.println("①" + beanFactory);
75         Work workService = (Work) beanFactory.getBean("work");
76         String status = workService.getStatus();
77         System.out.println("②" + status);
78     }
79 
80     @Override
81     public void afterPropertiesSet() throws Exception {
82         System.out.println("①afterPropertiesSet -> invoked");
83     }
84 
85     @Override
86     public void destroy() throws Exception {
87         System.out.println("①DisposableBean's destroy -> invoked");
88     }
89 
90     public void beforeDestroy() {
91         System.out.println("①beforeDestroy -> invoked");
92     }
93 }

Work.java

 1 package com.spring.pojo;
 2 
 3 import org.springframework.beans.BeansException;
 4 import org.springframework.beans.factory.*;
 5 import org.springframework.context.ApplicationContext;
 6 import org.springframework.context.ApplicationContextAware;
 7 
 8 public class Work implements BeanNameAware, BeanFactoryAware, ApplicationContextAware, InitializingBean, DisposableBean {
 9 
10     public String name;
11     public String age;
12 
13     public Work() {
14         System.out.println("②Constructor -> invoked");
15     }
16 
17     public Work(String name, String age) {
18         this.name = name;
19         this.age = age;
20     }
21 
22     public String getName() {
23         return name;
24     }
25 
26     public void setName(String name) {
27         System.out.println("②setName -> invoked");
28         this.name = name;
29     }
30 
31     public String getAge() {
32         return age;
33     }
34 
35     public void setAge(String age) {
36         this.age = age;
37     }
38 
39     public String getStatus() {
40         return this.name + ":" + this.age;
41     }
42 
43     public void initMethod() {
44         System.out.println("②initMethod -> invoked");
45     }
46 
47     @Override
48     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
49         System.out.println("②" + applicationContext);
50     }
51 
52     @Override
53     public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
54         System.out.println("②" + beanFactory);
55     }
56 
57     @Override
58     public void setBeanName(String s) {
59         System.out.println("②" + s);
60     }
61 
62     @Override
63     public void destroy() throws Exception {
64         System.out.println("②destroy -> invoked");
65     }
66 
67     @Override
68     public void afterPropertiesSet() throws Exception {
69         System.out.println("②afterPropertiesSet");
70     }
71 
72     public void destroyMethod() {
73         System.out.println("②destroyMethod -> invoked");
74     }
75 }

BeanProcessor.java

 1 package com.spring.pojo;
 2 
 3 import org.springframework.beans.BeansException;
 4 import org.springframework.beans.factory.config.BeanPostProcessor;
 5 
 6 public class BeanProcessor implements BeanPostProcessor {
 7 
 8     @Override
 9     public Object postProcessBeforeInitialization(Object o, String s) throws BeansException {
10         System.out.println("postProcessBeforeInitialization -> invoked");
11         return o;
12     }
13 
14     @Override
15     public Object postProcessAfterInitialization(Object o, String s) throws BeansException {
16         System.out.println("postProcessAfterInitialization -> invoked");
17         return o;
18     }
19 }

UserTest.java

 1 package com.spring.pojo;
 2 
 3 import com.spring.pojo.User;
 4 import org.springframework.context.support.AbstractApplicationContext;
 5 import org.springframework.context.support.ClassPathXmlApplicationContext;
 6 
 7 public class UserTest {
 8 
 9     public static void main(String[] args) {
10         AbstractApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
11         User service = (User) context.getBean("user");
12         service.show();
13     }
14 }

applicationContext.xml

<?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="com.spring.pojo.User"
          scope="prototype"
          init-method="initBean" destroy-method="beforeDestroy">
        <property name="name" value="祁连山"/>
        <!-- <property name="gender" value="男"/>
        <property name="service" ref="workService"/> -->
    </bean>

    <bean id="work" class="com.spring.pojo.Work"
        scope="prototype">
        <property name="name" value="android开发"/>
        <property name="age" value="三年"/>
    </bean>

    <bean id="beanProcessor" class="com.spring.pojo.BeanProcessor"/>
</beans>

⑤测试结果:
①Constructor -> invoked
①setName -> invoked
①user
①org.springframework.beans.factory.support.DefaultListableBeanFactory@3fcd000a: defining beans [user,work,beanProcessor]; root of factory hierarchy
②Constructor -> invoked
②setName -> invoked
②work
②org.springframework.beans.factory.support.DefaultListableBeanFactory@3fcd000a: defining beans [user,work,beanProcessor]; root of factory hierarchy
②org.springframework.context.support.ClassPathXmlApplicationContext@7c4633e7: startup date [Sun Nov 29 13:26:05 CST 2015]; root of context hierarchy
postProcessBeforeInitialization -> invoked
②afterPropertiesSet
postProcessAfterInitialization -> invoked
②android开发:三年
①org.springframework.context.support.ClassPathXmlApplicationContext@7c4633e7: startup date [Sun Nov 29 13:26:05 CST 2015]; root of context hierarchy
postProcessBeforeInitialization -> invoked
①afterPropertiesSet -> invoked
①initBean -> invoked
postProcessAfterInitialization -> invoked
①祁连山

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 对于SpringBean生命周期Spring在容器有5个生命周期阶段,它们分别是:实例化、属性设置、初始化、销毁以及单例实例化,每个阶段的bean都会触发一个对应的回调事件,让开发者能够在每个阶段做一些额外的处理。 ### 回答2: SpringBean 生命周期包括以下几个阶段: 1. Bean 实例化:Spring 在启动时会通过反射机制实例化 Bean。这是 Bean 生命周期的开始阶段。 2. Bean 属性设置:Spring 在实例化 Bean 后,会根据配置文件或注解等方式,将属性值注入到 Bean 。 3. Bean 初始化前置处理:如果 Bean 实现了 InitializingBean 接口,那么 Spring 会在属性设置完成后调用 Bean 的 afterPropertiesSet() 方法进行初始化前的处理。 4. Bean 初始化后置处理:如果 Bean 配置了 init-method 方法,或者在配置文件通过 init-method 属性指定了初始化方法,那么 Spring 会在初始化前置处理完成后调用该方法。 5. Bean 使用阶段:在初始化完成后,Bean 就可以被应用程序使用了。 6. Bean 销毁前置处理:如果 Bean 实现了 DisposableBean 接口,那么在关闭应用程序或手动销毁 Bean 时,Spring 会先调用 Bean 的 destroy() 方法进行销毁前的处理。 7. Bean 销毁后置处理:如果 Bean 配置了 destroy-method 方法,或者在配置文件通过 destroy-method 属性指定了销毁方法,那么 Spring 会在销毁前置处理完成后调用该方法。 在整个 Bean 生命周期,开发人员可以通过实现 InitializingBean 和 DisposableBean 接口,或者在配置文件指定 init-method 和 destroy-method 方法,来自定义 Bean 的初始化和销毁过程,并在这些过程进行一些特定的操作。 ### 回答3: SpringBean生命周期可以分为以下阶段: 1. 实例化:Spring通过Bean定义创建Bean的实例。这可以通过构造函数实例化,或者通过工厂方法来实现。 2. 属性赋值:SpringBean的属性值注入到Bean的实例。这可以通过依赖注入(DI)方式进行,也可以通过配置文件或注解来实现。 3. 初始化:在Bean实例化和属性赋值之后,Spring会调用Bean的初始化方法。这可以通过实现InitializingBean接口的afterPropertiesSet()方法,或者使用@PostConstruct注解来实现。 4. 使用:在初始化完成之后,Bean可以被使用,执行业务逻辑。 5. 销毁:当Bean不再需要时,Spring会调用Bean的销毁方法。这可以通过实现DisposableBean接口的destroy()方法,或者使用@PreDestroy注解来实现。 需要注意的是,在Bean的生命周期,可以通过配置文件或注解来控制Bean的创建和销毁方式。 总的来说,SpringBean生命周期包括实例化、属性赋值、初始化、使用和销毁这几个阶段。通过控制Bean的生命周期,我们可以在合适的时机执行一些特定的操作,如初始化资源、释放资源等。这样可以有效地管理Bean的生命周期,提高系统的性能和可维护性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值