Spring中與Bean相關的介面

cactusz發表於2017-07-06

package chapter22;

 

import org.springframework.beans.BeansException;

import org.springframework.beans.factory.BeanClassLoaderAware;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.BeanFactoryAware;

import org.springframework.beans.factory.BeanNameAware;

import org.springframework.beans.factory.DisposableBean;

import org.springframework.beans.factory.InitializingBean;

import org.springframework.context.ApplicationContext;

import org.springframework.context.ApplicationContextAware;

 

//如果被裝配的Bean實現了相應的介面,就可以在Bean中獲得相應的資訊。,或者進行某些操作。

public class HelloServiceImpl implements HelloService,

//以下同時為介面的呼叫的順序

BeanNameAware,//獲得Bean名,也就是<Bean>標籤的id屬性值。

BeanClassLoaderAware,//獲得裝載過程中的ClassLoader物件。

BeanFactoryAware,//獲得BeanFactory物件

ApplicationContextAware,//獲得ApplicationContext物件

InitializingBean, //在Bean的所有屬性設定完後,並且在呼叫完上面介面的方法後,呼叫此介面的afterPropertiesSet方法

DisposableBean //當銷燬Bean時,呼叫此介面的destroy方法

{

private String greeting;

public String getGreeting() {

// TODO Auto-generated method stub

return "hello "+greeting;

}

//以下同時為方法的呼叫的順序

public void setGreeting(String greeting)

{

this.greeting = greeting;

System.out.println("設定greeting屬性");

}

public void setBeanName(String name) {

System.out.println("BeanNameAware介面方法  "+name);

}

 

public void setBeanClassLoader(ClassLoader arg0) {

System.out.println("BeanClassLoaderAware介面方法  "+arg0);

}

public void setBeanFactory(BeanFactory arg0) throws BeansException {

System.out.println("BeanFactoryAware介面方法  "+arg0);

}

 

public void setApplicationContext(ApplicationContext applicationContext)

throws BeansException {

System.out.println("ApplicationContextAware介面方法  "+applicationContext);

}

public void afterPropertiesSet() throws Exception {

System.out.println("InitializingBean介面方法");

}

public  void initMethod(){

System.out.println("<bean>標籤的init-Method屬性指定的方法,此方法在afterPropertiesSet()之後呼叫");

}

 

public void destroy() throws Exception {

System.out.println("destroy");

}

public  void destroyMethod(){

System.out.println("<bean>標籤的destroy-Method屬性指定的方法,此方法在destroy()之後呼叫");

}

}

 

 

applicationContext.xml中的部分:

<bean id="greeting" class="chapter22.HelloServiceImpl" scope="prototype" init-method="initMethod" destroy-method="destroyMethod">

<property name="greeting" >

<value>yjz</value>

</property>

</bean>

相關文章