Spring容器启动过程

1、Spring容器的启动流程
Spring容器创建容器中的对象(执行构造函数)
②给对象的属性赋值(get或set方法)
③ 调用init方法(init方法)    
④contextgetBean方法把对象提取出来,调用业务逻辑方法
⑤当容器关闭的时候,执行destroy方法

2、代码如下
com.itheima.spring.initdestroy.helloworld.java
   
   
  1. package com.itheima.spring.initdestroy;
  2. public class helloworld {
  3. private String name;
  4. public String getName() {
  5. return name;
  6. }
  7. public void setName(String name) {
  8. this.name = name;
  9. System.out.println("set函数");
  10. }
  11. public helloworld(){
  12. System.out.println("构造函数");
  13. }
  14. public void init(){
  15. System.out.println("init");
  16. }
  17. public void destroy() {
  18. System.out.println("destroy");
  19. }
  20. public void hello() {
  21. System.out.println("你好");
  22. }
  23. }

com.itheima.spring.initdestroy.test.initdestroyTest.java
    
    
  1. package com.itheima.spring.initdestroy.test;
  2. import org.junit.Test;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5. import com.itheima.spring.initdestroy.helloworld;
  6. public class initdestroyTest {
  7. @Test
  8. public void test() {
  9. ApplicationContext context =
  10. new ClassPathXmlApplicationContext("applicationContext.xml");
  11. helloworld helloworld1 = (helloworld)context.getBean("helloworld");
  12. helloworld1.hello();
  13. //Spring 容器关闭
  14. ClassPathXmlApplicationContext applicationContext = (ClassPathXmlApplicationContext)context;
  15. applicationContext.close();
  16. }
  17. }

applicationContext.xml
    
    
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
  6. <!--
  7. 初始化方法:在构造函数执行之后,执行初始化方法
  8. init-method
  9. 销毁方法:在spring容器关闭时,自动执行销毁方法
  10. destroy-method
  11. -->
  12. <bean id="helloworld" class="com.itheima.spring.initdestroy.helloworld"
  13. init-method="init" destroy-method="destroy"></bean>
  14. </beans>
运行结果:
    
    
  1. 构造函数
  2. set函数
  3. init
  4. 你好
  5. destroy
(附件:有关Spring IOC的代码)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值