IT

Spring 현재 ApplicationContext 가져 오기 오기

lottoking 2020. 8. 24. 20:37
반응형

Spring 현재 ApplicationContext 가져 오기 오기


내 웹 애플리케이션에 Spring MVC를 사용하고 있습니다. 내 콩은 " spring-servlet.xml"파일에 기록 합니다.

이제 클래스가 MyClass필요한 스프링 빈을 사용하여 하여이 클래스에 액세스하고 싶습니다.

에서 spring-servlet.xml내가 회의 다음

<bean id="myClass" class="com.lynas.MyClass" />

이제 나는 이것을 사용하여 액세스해야합니다. ApplicationContext

ApplicationContext context = ??

내가 할 수 기능

MyClass myClass = (MyClass) context.getBean("myClass");

이 작업을 수행하는 방법 ??


만하면 ..

@Autowired
private ApplicationContext appContext;

또는이 인터페이스 구현 : ApplicationContextAware


링크 는 Bean이 아닌 클래스에서 어디서나 응용 프로그램을 얻는 가장 좋은 방법을 보여줍니다. 나는 그것이 매우 유용하다고 생각합니다. 당신도 똑같기를 바랍니다. 아래는 그것의 도시 인 코드입니다

새 클래스 ApplicationContextProvider.java 만들기

package com.java2novice.spring;

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

public class ApplicationContextProvider implements ApplicationContextAware{

    private static ApplicationContext context;

    public static ApplicationContext getApplicationContext() {
        return context;
    }

    @Override
    public void setApplicationContext(ApplicationContext ac)
            throws BeansException {
        context = ac;
    }
}

application-context.xml에 항목 추가

<bean id="applicationContextProvider"
                        class="com.java2novice.spring.ApplicationContextProvider"/>

어노테이션의 경우 (application-context.xml 대신)

@Component
public class ApplicationContextProvider implements ApplicationContextAware{
...
}

이와 같은 맥락을 얻으십시오.

TestBean tb = ApplicationContextProvider.getApplicationContext().getBean("testBean", TestBean.class);

건배 !!


Spring에 의해 인스턴스화되지 않은 HttpServlet 내에서 컨텍스트에 액세스해야하는 경우 (따라서 @Autowire도 ApplicationContextAware도 작동하지 않습니다) ...

WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());

또는

SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);

다른 응답 중 일부 는 이렇게하기 전에 두 번 생각하십시오.

new ClassPathXmlApplicationContext("..."); // are you sure?

... 현재 컨텍스트를 제공하지 않고 대신 다른 인스턴스를 생성합니다. 이는 1) 상당한 양의 메모리와 2) 빈이이 두 애플리케이션 컨텍스트간에 공유되지 않음을 의미합니다.


JsonDeserializer와 같이 Spring에 의해 인스턴스화되지 않은 클래스를 구현하는 경우 다음을 사용할 수 있습니다.

WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
MyClass myBean = context.getBean(MyClass.class);


이것을 코드에 추가하십시오.

@Autowired
private ApplicationContext _applicationContext;

//Add below line in your calling method
MyClass class = (MyClass) _applicationContext.getBean("myClass");

// Or you can simply use this, put the below code in your controller data member declaration part.
@Autowired
private MyClass myClass;

이것은 단순히 myClass를 응용 프로그램에 삽입합니다.


Vivek의 답변을 기반으로하지만 다음이 더 나을 것이라고 생각합니다.

@Component("applicationContextProvider")
public class ApplicationContextProvider implements ApplicationContextAware {

    private static class AplicationContextHolder{

        private static final InnerContextResource CONTEXT_PROV = new InnerContextResource();

        private AplicationContextHolder() {
            super();
        }
    }

    private static final class InnerContextResource {

        private ApplicationContext context;

        private InnerContextResource(){
            super();
        }

        private void setContext(ApplicationContext context){
            this.context = context;
        }
    }

    public static ApplicationContext getApplicationContext() {
        return AplicationContextHolder.CONTEXT_PROV.context;
    }

    @Override
    public void setApplicationContext(ApplicationContext ac) {
        AplicationContextHolder.CONTEXT_PROV.setContext(ac);
    }
}

인스턴스 메서드에서 정적 필드로 쓰는 것은 나쁜 습관이며 여러 인스턴스가 조작되는 경우 위험합니다.


1 단계 : 수업에 다음 코드 삽입

@Autowired
private ApplicationContext _applicationContext;

2 단계 : Getter 및 Setter 작성

3 단계 : 빈이 정의 된 xml 파일에 autowire = "byType"정의


Spring 애플리케이션에서 애플리케이션 컨텍스트를 얻는 방법은 여러 가지가 있습니다. 다음은 다음과 같습니다.

  1. ApplicationContextAware를 통해 :

    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    
    public class AppContextProvider implements ApplicationContextAware {
    
    private ApplicationContext applicationContext;
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
    }
    

여기 setApplicationContext(ApplicationContext applicationContext)메서드는 applicationContext를 얻습니다.

  1. Autowired를 통해 :

    @Autowired
    private ApplicationContext applicationContext;
    

여기서 @Autowired키워드는 applicationContext를 제공합니다.

자세한 내용은 이 스레드를 방문하십시오.

감사 :)


또 다른 방법은 서블릿을 통해 applicationContext를 주입하는 것입니다.

이것은 Spring 웹 서비스를 사용할 때 종속성을 주입하는 방법의 예입니다.

<servlet>
        <servlet-name>my-soap-ws</servlet-name>
        <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
        <init-param>
            <param-name>transformWsdlLocations</param-name>
            <param-value>false</param-value>
        </init-param>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:my-applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>5</load-on-startup>

</servlet>

다른 방법은 아래와 같이 web.xml에 애플리케이션 컨텍스트를 추가하는 것입니다.

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/classes/my-another-applicationContext.xml
        classpath:my-second-context.xml
    </param-value>
</context-param>

기본적으로 서블릿에게 이러한 컨텍스트 파일에 정의 된 빈을 찾아야한다고 알려 주려고합니다.


ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-servlet.xml");

그런 다음 Bean을 검색 할 수 있습니다.

MyClass myClass = (MyClass) context.getBean("myClass");

참조 : springbyexample.org

참고 URL : https://stackoverflow.com/questions/21827548/spring-get-current-applicationcontext

반응형