spring中bean的生命周期

package com.spring.helloworld;

public class Car {
    public Car(){
        System.out.println("先调用构造器方法");
    }
    private String company;
    private String brand;
    private int maxSpeed;
    public void setCompany(String company) {
        System.out.println("2:调用set方法");
        this.company = company;
    }
    public void setBrand(String brand) {
        this.brand = brand;
    }
    public void setMaxSpeed(int maxSpeed) {
        this.maxSpeed = maxSpeed;
    }
    @Override
    public String toString() {
        return "Car [company=" + company + ", brand=" + brand + ", maxSpeed="
                + maxSpeed + "]";
    }
    public void init(){
        System.out.println("3:调用init方法");
    }
    public void destroy(){
        System.out.println("4:关闭IOC的时候 ,调用destroy");
    }
    
}

在配置文件中进行设定哪个方法是初始化方法。哪个是销毁方法

<bean  id="car" class="com.spring.helloworld.Car" 
    init-method="init"
    destroy-method="destroy"
    p:company="Audi"  p:brand="shanghai" p:maxSpeed="450"
    />
package com.spring.helloworld;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {
        //1:创建IOC容器
        ClassPathXmlApplicationContext act=new ClassPathXmlApplicationContext("applicationContext.xml");
        //2:从IOC中获得Bean实例
        Car car=(Car) act.getBean("car");
        System.out.println(car);
        act.close();
    }
}

 

2:在进行初始化前可以进行一些操作

 1 package com.spring.helloworld;
 2 
 3 import org.springframework.beans.BeansException;
 4 import org.springframework.beans.factory.config.BeanPostProcessor;
 5 
 6 public class MyBeanPostProcessor implements BeanPostProcessor{
 7 
 8     @Override
 9     public Object postProcessAfterInitialization(Object bean, String beanName)
10             throws BeansException {
11         System.out.println("初始化方法后进行");
12         System.out.println(bean+"--"+beanName);
13         return bean;
14     }
15 
16     @Override
17     public Object postProcessBeforeInitialization(Object bean, String beanName)
18             throws BeansException {
19         System.out.println("初始化方法前进行");
20         System.out.println(bean+"--"+beanName);
21         return bean;
22     }
23 
24 }

 

<!-- 需要继承BeanPostProcessor方法
        bean:bean实例本身
        beanName:IOC配置的bean名称。
        返回值:是实际上返回给用户的那个bean,注意:可以在以上两个方法中修改返回的bean。甚至返回一个新的bean。就是可以在这两个方法中修改set中的值。
     -->
    <bean class="com.spring.helloworld.MyBeanPostProcessor"></bean>

 

posted @ 2017-11-27 23:39  陆伟  阅读(160)  评论(0编辑  收藏  举报