Spring ---XXXAware 接口 XXXCapable接口

1.Spring 中 XXXAware 接口

XXXAware 表示對XXX可以感知,實現 XXXAware接口的類 表示 這個類需要XXX

如果某個類 需要使用spring的一些東西,通過實現XXXAware接口就可以了,Spring 看到會給你送過來,接收方式 是通過  實現XXXAware接口的唯一方法set方法來接收

例如 某個類 需要使用ApplicationContext上下文,就可以實現如下

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

//這個類 需要使用ApplicationContext ,只需要 實現ApplicationContextAware接口
//spring 會自動調用 setApplicationContext()方法 把ApplicationContext傳給我們
//我們 用this.applicationContext 接收就可以了
public class SpringAwareTest implements ApplicationContextAware{

	private ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}
}

2.Spring 中 XXXCapable接口

XXXCapable 表示 有提供XXX的能力

實現XXXCapable接口的類 告訴Spring 它有提供XXX的能力,如果Spring需要XXX,可以調用 這個類的get()方法來獲得

例如 某個類實現了 EnvironmentCapable接口,表示告訴Spring 它具有Environment能力,它可以提供Environment,如果Spring需要Environment,可以調用它的 getEnvironment方法來獲得。

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章