码迷,mamicode.com
首页 > 编程语言 > 详细

spring中bean的生命周期

时间:2017-11-28 01:35:51      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:set   style   继承   cto   实例   stp   pos   图片   contex   

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>

 

spring中bean的生命周期

标签:set   style   继承   cto   实例   stp   pos   图片   contex   

原文地址:http://www.cnblogs.com/bulrush/p/7906739.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!