bean的PostConstruct和PreDestroy

Spring从2.5开始支持@PostConstruct和@PreDestroy注解。他们的功能相当于init-method和destroy-method,但是在一个Bean中,可以定义多个@PostConstruct和@PreDestroy。

就我个人的观点来说,我是不希望我的团队在代码中大量使用这些方法。这些方法,总是让人感觉代码是在以跳跃的方式进行运作,而不是基于常规的逻辑。 漏洞和一些预料之外的方法,总是出现在这样的配置之中….

使用多个PostConstruct和PreDestroy的源代码驾驶员package com.spring.bean;import org.springframework.stereotype.Component;/** * 一个简单通过注解配置的bean,驾驶员 * @author 范芳铭 * * */{private String name;public String getName() {return name;}(String name) {this.name = name;}}小汽车package com.spring.bean;import javax.annotation.PostConstruct;import javax.annotation.PreDestroy;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;/** * 一个简单通过注解配置的bean * @author 范芳铭 * * */{private People people;public Car(){System.out.println(“Car:默认构造函数”);}public People getPeople() {return people;}(People people) {System.out.println(“– @Autowired 参数注入”);this.people = people;}(){System.out.println(“– 运行 ini1.”);}(){System.out.println(“– 运行 ini2.”);}(){System.out.println(“– 运行 destory1.”);}(){System.out.println(“– 运行 destory2.”);}@Overridepublic String toString(){return “Role类被调用: “+this.people.getName();}}模拟容器启动和关闭package com.spring.bean;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;{(String[] args){//模拟启动容器ApplicationContext ctx = newClassPathXmlApplicationContext(“bean.xml”);//模拟容器关闭((ClassPathXmlApplicationContext)ctx).destroy();}}

配置bean.xml

====”http://www.springframework.org/schema/task”xsi:schemaLocation=””>>运行结果

Car:默认构造函数 – @Autowired 参数注入 – 运行 ini1. – 运行 ini2. – 运行 destory1. – 运行 destory2.

,只剩下一条路,那就是成功的路。

bean的PostConstruct和PreDestroy

相关文章:

你感兴趣的文章:

标签云: