spring学习总结(七):IOC & DI 配置Bean之bean的生命周期及bean的配置方式

IOC & DI 配置Bean之bean的生命周期及bean的配置方式


Bean的生命周期

IOC 容器中 Bean 的生命周期方法

  • Spring IOC 容器可以管理 Bean 的生命周期, Spring 允许在 Bean 生命周期的特定点执行定制的任务
  • 在 Bean 的声明里设置 init-methoddestroy-method 属性, 为 Bean 指定初始化和销毁方法.
Car.java
package com.xyc.spring.cycle;

/**
 * 
 * @ClassName:  Car   
 * @Description:Spring IOC容器及生命周期测试
 * @author: xyc 
 * @date:   2016年11月26日 下午4:25:23   
 *
 */
public class Car {

    private String brand;


    public void setBrand(String brand) {
        System.out.println("Car setBrand.........");
        this.brand = brand;
    }


    public void init(){
        System.out.println("Car init...........");
    }
    
    public void destory(){
        System.out.println("Car destory..........");
    }
    
    public Car() {
        System.out.println("Car Contruator...");
    }


    @Override
    public String toString() {
        return "Car [brand=" + brand + "]";
    }
    
    
}

bean-cycle.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.xsd">


	<!-- 在 Bean 的声明里设置 init-method 和 destroy-method 属性, 为 Bean 指定初始化和销毁方法. -->
	<bean id="car" class="com.xyc.spring.cycle.Car" init-method="init" destroy-method="destory">
		<property name="brand" value="BMW"></property>
	</bean>

</beans>

ApplicationCycle.java
package com.xyc.main;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.xyc.spring.cycle.Car;

/**
 * 
 * @ClassName:  ApplicationCycle   
 * @Description:测试spring IOC容器及生命周期
 * @author: xyc 
 * @date:   2016年11月26日 下午4:30:05   
 *
 */
public class ApplicationCycle {

    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPat
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值