package com.h3.customer.services; import javax.annotation.postconstruct; import javax.annotation.predestroy; public class customerservice { string message; public string getmessage() { return message; } public void setmessage(string message) { this.message = message; } @postconstruct public void initit() throws exception { system.out.println("init method after properties are set : " + message); } @predestroy public void cleanup() throws exception { system.out.println("spring container is destroy! customer clean up"); } }
<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-2.5.xsd"> <bean class="org.springframework.context.annotation.commonannotationbeanpostprocessor" /> <bean id="customerservice" class="com.h3.customer.services.customerservice"> <property name="message" value="i'm property message" /> </bean> </beans>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:annotation-config /> <bean id="customerservice" class="com.h3.customer.services.customerservice"> <property name="message" value="i'm property message" /> </bean> </beans>
执行结果
package com.h3.common; import org.springframework.context.configurableapplicationcontext; import org.springframework.context.support.classpathxmlapplicationcontext; import com.h3.customer.services.customerservice; public class app { public static void main( string[] args ) { configurableapplicationcontext context = new classpathxmlapplicationcontext(new string[] {"spring-customer.xml"}); customerservice cust = (customerservice)context.getbean("customerservice"); system.out.println(cust); context.close(); } }
输出结果
init method after properties are set : im property message com.h3.customer.services.customerservice@47393f ... info: destroying singletons in org.springframework.beans.factory. support.defaultlistablebeanfactory@77158a: defining beans [customerservice]; root of factory hierarchy spring container is destroy! customer clean up