Spring 에서 Application ContextAware 사용 설명

Spring 에서 Aware 관련 인 터 페 이 스 를 제공 합 니 다. 예 를 들 어 BeanFactory Aware, Application ContextAware, Resource LoaderAware, ServletContextAware 등 이 있 습 니 다. 이러한 Aware 인 터 페 이 스 를 만 든 Bean 은 초기 에 해당 하 는 자원 을 얻 을 수 있 습 니 다. 예 를 들 어 실제 BeanFactory Aware 의 Bean 은 초기 에 Spring 용기 에 BeanFactory 의 인 스 턴 스 를 주입 합 니 다.실제 애플 리 케 이 션 ContextAware 의 Bean 은 Bean 이 초기 화 되면 애플 리 케 이 션 Context 의 인 스 턴 스 등 을 주입 합 니 다.Bean 이 BeanFactory, ApplicationContextAware 를 얻 는 실례 적 인 목적 은 무엇 입 니까? 일반적인 목적 은 일부 파일 자원 의 액세스, 관련 정보 자원 또는 주 입 된 실례 가 제공 하 는 메커니즘 을 얻 는 것 입 니 다. 예 를 들 어 ApplicationContextAware 는 publishEvent () 방법 을 제공 하고 Observer 모드 를 바탕 으로 하 는 이벤트 전파 메커니즘 을 지원 할 수 있 습 니 다.응용 프로그램 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());

빈 의 경우 스프링 에 대한 의존 도 를 낮 춰 기 존 틀 에서 벗 어 나 기 쉽다.

좋은 웹페이지 즐겨찾기