>  기사  >  Java  >  SpringBoot ApplicationContextAware 확장 인터페이스를 사용하는 방법

SpringBoot ApplicationContextAware 확장 인터페이스를 사용하는 방법

王林
王林앞으로
2023-05-15 17:04:06916검색

ApplicationContextAware 인터페이스:

public interface ApplicationContextAware extends Aware {
    void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}

우선, Aware 인터페이스는 이것이 사용자가 사용할 springboot 확장임을 알고 있습니다. 여기서는 setApplicationContext 메소드가 제공되어 이 컨텍스트를 받을 수 있습니다. Spring 컨테이너를 얻는 방법을 알고 싶습니다. 컨텍스트 ApplicationContext의 목적은 무엇입니까? 컨텍스트를 가져오고 컨텍스트의 특성에 따라 작업을 수행합니다.

ApplicationContext 개체의 메서드를 살펴보겠습니다.

SpringBoot ApplicationContextAware 확장 인터페이스를 사용하는 방법

AbstractApplicationContext 구현 클래스의 메서드를 살펴보겠습니다.

    public Object getBean(String name) throws BeansException {this.assertBeanFactoryActive();return this.getBeanFactory().getBean(name);}
    public <T> T getBean(String name, Class<T> requiredType) throws BeansException {this.assertBeanFactoryActive();return this.getBeanFactory().getBean(name, requiredType);}
    public Object getBean(String name, Object... args) throws BeansException {this.assertBeanFactoryActive();return this.getBeanFactory().getBean(name, args);}
    public <T> T getBean(Class<T> requiredType) throws BeansException {this.assertBeanFactoryActive();return this.getBeanFactory().getBean(requiredType);}
    public <T> T getBean(Class<T> requiredType, Object... args) throws BeansException {this.assertBeanFactoryActive();return this.getBeanFactory().getBean(requiredType, args);}
    public <T> ObjectProvider<T> getBeanProvider(Class<T> requiredType) {this.assertBeanFactoryActive();return this.getBeanFactory().getBeanProvider(requiredType);}
    public <T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType) {this.assertBeanFactoryActive();return this.getBeanFactory().getBeanProvider(requiredType);}
    public boolean containsBean(String name) {return this.getBeanFactory().containsBean(name);}
    public boolean isSingleton(String name) throws NoSuchBeanDefinitionException {this.assertBeanFactoryActive();return this.getBeanFactory().isSingleton(name);}
    public boolean isPrototype(String name) throws NoSuchBeanDefinitionException {this.assertBeanFactoryActive();return this.getBeanFactory().isPrototype(name);}

여기서 getBean() 메서드가 익숙해 보이는 것을 볼 수 있습니다. 우리가 처음 spring을 배울 때는 spring을 사용하지 않았습니다. 스캐폴딩 프로젝트를 생성할 때, bean을 얻는 방법은 일반적으로 classPathContextLoader로 bean의 xml 파일을 스캔하고 이를 구문 분석하여 ApplicationCOntext 객체를 형성한 다음 getBean 메소드를 호출하여 가져오는 것입니다. 인스턴스 빈.

이로부터 우리의 주요 응용 방법은 이 getBean 메소드를 사용하는 것임을 알 수 있습니다. 그러면 여러 메소드를 통해 동적으로 Bean을 주입할 수 있으므로 주입된 Bean을 정적 메소드에서 사용할 수 없다는 문제를 생각하는 것은 어렵지 않습니다.

다음으로 이 문제를 재현해 보겠습니다. 다음 코드를 살펴보겠습니다.

public class JsonGetter {
@Resource
private UuidGetter uuidGetter;
public static string Test(){
       return uuidGetter.getUuid();
}
public static JsONobject set0bjectToJsonObject(object data){
       return JsoNobject.parseObject(String.valueof(JsONObject.toJSON(data)));
}
public static JsONObject setStringTO3son0bject(String data) { return JsONObject.parseObject(data);
}

정적 Test 메소드에서 주입된 Bean을 호출하면 다음과 같은 설명이 표시됩니다. 로딩 메커니즘 및 로딩 덕분입니다. 클래스의 순서에 따라 정적 속성 및 정적 코드 블록이 먼저 로드됩니다(정적이 우선순위를 갖습니다). 여기서는 정적 메소드를 로드할 Bean 인스턴스가 없으므로 자연스럽게 오류가 보고됩니다.

어떻게 해결하나요? Spring이 Bean 객체를 얻을 때 getBean 메소드를 호출하고 컨테이너가 로드될 때 Spring 컨테이너의 컨텍스트를 정적으로 저장하는 아이디어를 채택할 수 있습니다.

@Component
@Lazy(value = false)
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {
    /**
     * 将上下文静态设置,在初始化组件时就进行静态上下文的覆盖(这个覆盖是将远spring容器的上下文对象引用加到我们预定设置)
     */
    private static ApplicationContext applicationContext = null;
    public static ApplicationContext getApplicationContext() {
        assertContextInjected();
        return applicationContext;
    }
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        assertContextInjected();
        return (T) applicationContext.getBean(name);
    }
    public static  <T> T getBean(Class<T> beanType) {
        assertContextInjected();
        return applicationContext.getBean(beanType);
    }
    @Override
    public void setApplicationContext(@NotNull ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.applicationContext = applicationContext;
    }
    @Override
    public void destroy() {
        applicationContext = null;
    }
    private static void assertContextInjected() {
        Assert.notNull(applicationContext,
                "applicationContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");
    }
    public static void pushEvent(ApplicationEvent event){
        assertContextInjected();
        applicationContext.publishEvent(event);
    }
}

여기서 주의해야 할 것은 정의입니다. 정적 멤버 변수 ApplicationContext 할당 및 확인:

    /**
     * 将上下文静态设置,在初始化组件时就进行静态上下文的覆盖(这个覆盖是将远spring容器的上下文对象引用加到我们预定设置)
     */
    private static ApplicationContext applicationContext = null;

정적 컨텍스트 적용을 달성하기 위해 확장 인터페이스의 메서드를 다시 작성합니다.

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

이를 얻는 메서드를 공개하고 공유하기 쉽게 만듭니다.

    public static ApplicationContext getApplicationContext() {
        assertContextInjected();
        return applicationContext;
    }

아직 모르겠습니다. 이것을 작성한 후에는 이해가 되지 않습니다. 스프링 컨텍스트 객체를 정적으로 재정의하기 위해 이러한 방식으로 구성 요소를 정의하는 요점은 무엇입니까?

당황하지 마세요. 이 클래스의 메서드를 살펴보겠습니다.

public class AppContext {
    static transient ThreadLocal<Map<String, String>> contextMap = new ThreadLocal<>();
    ......省略n行业务代码
    public static void fillLoginContext() {
        DingAppInfo appInfo = SpringContextHolder.getBean(DingAppInfoService.class).findAppInfo(APP_CODE);
        setDingVerifyInfo(appInfo);
        CloudChatAppInfo cloudChatAppInfo = SpringContextHolder.getBean(CloudChatAppInfoService.class).findAppInfo(APP_CODE);
        setCloudChatInfo(cloudChatAppInfo);
    }
    public static void clear() {
        contextMap.remove(); //本地线程的remove方法极其重要,注意每次给它使用之后一定要调用remove清理,防止内存泄露。
    }
}

위 예제 코드에서 라이브러리 검사 작업이 수행된 것을 확인했습니다.

DingAppInfo appInfo = SpringContextHolder.getBean(DingAppInfoService.class).findAppInfo(APP_CODE);

위 내용은 SpringBoot ApplicationContextAware 확장 인터페이스를 사용하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제