Spring容器启动过程

    xiaoxiao2021-03-26  32

    1、Spring容器的启动流程 Spring容器创建容器中的对象(执行构造函数) ②给对象的属性赋值(get或set方法) ③ 调用init方法(init方法)     ④contextgetBean方法把对象提取出来,调用业务逻辑方法 ⑤当容器关闭的时候,执行destroy方法 2、代码如下 com.itheima.spring.initdestroy.helloworld.java package com.itheima.spring.initdestroy;public class helloworld { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; System.out.println("set函数"); } public helloworld(){ System.out.println("构造函数"); } public void init(){ System.out.println("init"); } public void destroy() { System.out.println("destroy"); } public void hello() { System.out.println("你好"); }} com.itheima.spring.initdestroy.test.initdestroyTest.java package com.itheima.spring.initdestroy.test;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.itheima.spring.initdestroy.helloworld;public class initdestroyTest { @Test public void test() { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); helloworld helloworld1 = (helloworld)context.getBean("helloworld"); helloworld1.hello(); //Spring 容器关闭 ClassPathXmlApplicationContext applicationContext = (ClassPathXmlApplicationContext)context; applicationContext.close(); }} 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-2.5.xsd"> <!-- 初始化方法:在构造函数执行之后,执行初始化方法 init-method 销毁方法:在spring容器关闭时,自动执行销毁方法 destroy-method --> <bean id="helloworld" class="com.itheima.spring.initdestroy.helloworld" init-method="init" destroy-method="destroy"></bean> </beans> 运行结果: 构造函数set函数init你好destroy (附件:有关Spring IOC的代码)
    转载请注明原文地址: https://ju.6miu.com/read-662943.html

    最新回复(0)