JAVA|JAVA 核心笔记 || [xxx] Spring 之 Bean 生命周期
Bean 生命周期
- init-method 配置初始化调用方法
- destroy-method 配置销毁调用方法
用法App.java
import com.mj.bean.BeanLife;
import com.mj.bean.BeanSay;
import com.mj.bean.BeanAnimal;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import java.io.FileNotFoundException;
public class App {public static void main(String args[]) throws FileNotFoundException{
//ClassPathXmlApplicationContext
ApplicationContext context = new ClassPathXmlApplicationContext("Bean.xml");
BeanSay sa = (BeanSay) context.getBean("BeanSay");
sa.setMsg("__Spring");
sa.talk();
//FileSystemXmlApplicationContext
ApplicationContext fileContext = new FileSystemXmlApplicationContext("/src/Bean.xml");
BeanSay sa1 = (BeanSay) fileContext.getBean("BeanSay");
sa1.setMsg("=Spring====");
sa1.talk();
ApplicationContext animalContext = new ClassPathXmlApplicationContext("Bean.xml");
BeanAnimal ani =(BeanAnimal) animalContext.getBean("Animal");
ani.setAnimalName("dog");
ani.showAnimal();
BeanAnimal animal =(BeanAnimal) animalContext.getBean("Animal");
animal.setAnimalName("pig");
animal.showAnimal();
// init methoddestroy method
BeanLife life = (BeanLife) context.getBean("BeanLife");
life.showName();
}
}
BeanLife.java
package com.mj.bean;
public class BeanLife {
privateString beanName = "BeanName=BeanLife";
public void setBeanName(String beanName) {
this.beanName = beanName;
}publicvoid showName(){
System.out.println("=Bean Name="+beanName);
}public void init(){
System.out.println("[BeanLife init]");
}public void destroy(){
System.out.println("[BeanLife destroy]");
}}
Bean.xml
【JAVA|JAVA 核心笔记 || [xxx] Spring 之 Bean 生命周期】运行
[BeanLife init]
=Bean Name=BeanLife
推荐阅读
- JAVA(抽象类与接口的区别&重载与重写&内存泄漏)
- EffectiveObjective-C2.0|EffectiveObjective-C2.0 笔记 - 第二部分
- 期刊|期刊 | 国内核心期刊之(北大核心)
- Android中的AES加密-下
- 事件代理
- Java|Java OpenCV图像处理之SIFT角点检测详解
- java中如何实现重建二叉树
- 【读书笔记】贝叶斯原理
- 【韩语学习】(韩语随堂笔记整理)
- 数组常用方法一