Spring 에서 Application ContextAware 사용 설명
ApplicationContextAware.java
public interface ApplicationContextAware {
void setApplicationContext(ApplicationContext context);
}
우리 쪽 에 서 는 어떻게 실제 응용 프로그램 ContextAware 를 통 해 응용 프로그램 Context 를 주입 하여 사건 전 파 를 실현 하 는 지 시범 을 보 여 줍 니 다. 먼저 우리 의 HelloBean 은 다음 과 같 습 니 다.
HelloBean.java
package onlyfun.caterpillar;
import org.springframework.context.*;
public class HelloBean implements ApplicationContextAware {
private ApplicationContext applicationContext;
private String helloWord = "Hello!World!";
public void setApplicationContext(ApplicationContext context) {
this.applicationContext = context;
}
public void setHelloWord(String helloWord) {
this.helloWord = helloWord;
}
public String getHelloWord() {
applicationContext.publishEvent(
new PropertyGettedEvent("[" + helloWord + "] is getted"));
return helloWord;
}
}
applicationContext 는 Spring 용기 에 주입 되 며, PublishEvent () 방법 은 applicationEvent 를 계승 하 는 대상 이 필요 합 니 다. 우리 의 Property Getted Event 는 applicationEvent 를 계승 합 니 다. 다음 과 같 습 니 다.
PropertyGettedEvent.java
package onlyfun.caterpillar;
import org.springframework.context.*;
public class PropertyGettedEvent extends ApplicationEvent {
public PropertyGettedEvent(Object source) {
super(source);
}
}
응용 프로그램 Context 가 publishEvent () 를 실행 하면 실제 응용 프로그램 Listener 인터페이스의 대상 을 자동 으로 찾 아 해당 사건 이 발생 했 음 을 알 립 니 다. 우 리 는 Property GettedListener 를 다음 과 같이 만 들 었 습 니 다.
PrppertyGettedListener.java
package onlyfun.caterpillar;
import org.springframework.context.*;
public class PropertyGettedListener implements ApplicationListener {
public void onApplicationEvent(ApplicationEvent event) {
System.out.println(event.getSource().toString());
}
}
Listener 는 반드시 실례 화 되 어야 합 니 다. 이것 은 Bean 정의 파일 에서 정의 할 수 있 습 니 다.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="propertyGetterListener" class="onlyfun.caterpillar.PropertyGettedListener"/>
<bean id="helloBean" class="onlyfun.caterpillar.HelloBean">
<property name="helloWord"><value>Hello!Justin!</value></property>
</bean>
</beans>
우 리 는 사건 전파 의 운행 을 측정 하기 위해 테스트 프로그램 을 썼 다.
Test.java
package onlyfun.caterpillar;
import org.springframework.context.*;
import org.springframework.context.support.*;
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
HelloBean hello = (HelloBean) context.getBean("helloBean");
System.out.println(hello.getHelloWord());
}
}
실행 결 과 는 다음 과 같다.
log4j:WARN No appenders could be found for logger
(org.springframework.beans.factory.xml.XmlBeanDefinitionReader).
log4j:WARN Please initialize the log4j system properly.
org.springframework.context.support.ClassPathXmlApplicationContext:
displayName=[org.springframework.context.support.ClassPathXmlApplicationContext;
hashCode=33219526]; startup date=[Fri Oct 29 10:56:35 CST 2004];
root of ApplicationContext hierarchy
[Hello!Justin!] is getted
Hello!Justin!
이상 은 실제 이벤트 전 파 를 통 해 실제 Aware 인터페이스 가 대응 하 는 대상 을 얻 은 후에 할 수 있 는 동작 입 니 다. 마찬가지 로 리 소스 LoaderAware 인터페이스 도 만 들 수 있 습 니 다.
ResourceLoaderAware.java
public interface ResourceLoaderAware {
void setResourceLoader(ResourceLoader loader);
}
실제 리 소스 로 더 의 빈 은 리 소스 로 더 의 인 스 턴 스 를 얻 을 수 있 습 니 다. 그러면 getResource () 방법 을 사용 할 수 있 습 니 다. 이것 은 파일 자원 을 액세스 해 야 하 는 빈 에 게 상당히 유용 합 니 다.기본적으로 Spring 은 이러한 Aware 와 관련 된 인 터 페 이 스 를 제공 하지만 Bean 에서 이러한 인 터 페 이 스 를 실현 하면 Spring 과 의존 이 발생 하 더 라 도 다른 측면 에서 볼 때 Bean 에서 이 인 터 페 이 스 를 직접 실현 할 수 있 지만 setter 를 통 해 의존 주입 을 완성 할 수 있 습 니 다. 예 를 들 어:
HelloBean.java
package onlyfun.caterpillar;
import org.springframework.context.*;
public class HelloBean {
private ApplicationContext applicationContext;
private String helloWord = "Hello!World!";
public void setApplicationContext(ApplicationContext context) {
this.applicationContext = context;
}
public void setHelloWord(String helloWord) {
this.helloWord = helloWord;
}
public String getHelloWord() {
applicationContext.publishEvent(new PropertyGettedEvent("[" + helloWord + "] is getted"));
return helloWord;
}
}
이번에 우 리 는 실제 응용 프로그램 ContextAware 가 없 음 을 주의 하 십시오. 우 리 는 프로그램 에서 응용 프로그램 Context 인 스 턴 스 를 스스로 주입 할 수 있 습 니 다.
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
HelloBean hello = (HelloBean) context.getBean("helloBean");
hello.setApplicationContext(context);
System.out.println(hello.getHelloWord());
빈 의 경우 스프링 에 대한 의존 도 를 낮 춰 기 존 틀 에서 벗 어 나 기 쉽다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.