三个文件都有改动:
package test; public class HelloWorld { private String message; public String getMessage() { return message; } public void setMessage(String message) { System.out.println("Your Message :"+message); } public void init() { System.out.println("bean开始进入"); } public void destroy() { System.out.println("bean被销毁"); } }
package test; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.core.io.ClassPathResource; public class MainApp { public static void main(String[] args) { //注意这里是AbstractApplicationContext,只有这个类有registerShutdownHook()方法 AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); HelloWorld obj = (HelloWorld) context.getBean("helloworld"); obj.getMessage(); context.registerShutdownHook(); } }
<?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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd " > <bean id="helloworld" class="test.HelloWorld" init-method = "init" destroy-method = "destroy"> <property name="message" value="你好世界"></property> </bean> </beans>