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 method   destroy method
        BeanLife life = (BeanLife) context.getBean("BeanLife");
        life.showName();

    }
}

BeanLife.java

package com.mj.bean;

public class BeanLife {
    private  String beanName = "BeanName=BeanLife";

    public void setBeanName(String beanName) {
        this.beanName = beanName;
    }

    public  void 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





    
        
    

    
    
        
    

    
        
    


运行

[BeanLife init]
=Bean Name=BeanLife

你可能感兴趣的:(JAVA 核心笔记 || [xxx] Spring 之 Bean 生命周期)