这里是 InitHelloWorld.java 文件的内容:
package com.tutorialspoint;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.BeansException;
public class InitHelloWorld implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("BeforeInitialization : " + beanName);
return bean; // you can return any other object as well
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("AfterInitialization : " + beanName);
return bean; // you can return any other object as well
}
}
下面是 MainApp.java 文件的内容。在这里,你需要注册一个在 ?AbstractApplicationContext
? 类中声明的关闭? hook
? 的 ?registerShutdownHook()
?方法。它将确保正常关闭,并且调用相关的 ?destroy
? 方法。
package com.tutorialspoint;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();
context.registerShutdownHook();
}
}
下面是 ?init
? 和 ?destroy
? 方法需要的配置文件 Beans.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-3.0.xsd">
?
<bean id="helloWorld" class="com.tutorialspoint.HelloWorld"
init-method="init" destroy-method="destroy">
<property name="message" value="Hello World!"/>
</bean>
?
<bean class="com.tutorialspoint.InitHelloWorld" />
?
</beans>
一旦你创建源代码和 ?bean
? 配置文件完成后,我们就可以运行该应用程序。如果你的应用程序一切都正常,将输出以下信息:
BeforeInitialization : helloWorld
Bean is going through init.
AfterInitialization : helloWorld
Your Message : Hello World!
Bean will destroy now.
标签:Spring IoC
相关阅读 >>
更多相关阅读请进入《Spring IoC》频道 >>
深入理解Java虚拟机 JVM高级特性与实践 周志明 第3版
这是一部从工作原理和工程实践两个维度深入剖析JVM的著作,是计算机领域公认的经典。