第五章 Spring Bean的初始化和销毁

来源:互联网 发布:full node bitcoin 编辑:程序博客网 时间:2024/05/21 17:09

1>Java配置方式
使用@Bean的initMethod和destroyMethod(相当于XML配置的init-method和destroy-method)
2>注解方式
使用@PostConstruct和@PreDestroy

本章Demo是基于上一章(添加AOP支持)
一、使用方式1

package demo2.service;import javax.annotation.PostConstruct;import javax.annotation.PreDestroy;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Service;@Servicepublic class DemoService {    @Value(value="world")    private String test;    public void sayDemo(String word) {        System.out.println("Hello " + word);    }    @PostConstruct  //1    public void init() {        System.out.println("init demo service");    }    @PreDestroy  //2    public void destroy() {        System.out.println("destroy demo service");    }}

1.@PostConstruct,在构造函数执行完之后执行
2.@PreDestroy,在Bean销毁之前执行

运行结果为

init demo service开始执行方法:sayDemoHello Springdestroy demo service
0 0
原创粉丝点击