Java Bean에서 web.xml 속성에 액세스하는 방법이 있습니까?

StackOverflow https://stackoverflow.com/questions/41659

  •  09-06-2019
  •  | 
  •  

문제

웹 컨테이너와 전혀 연결되지 않은 Bean 또는 Factory 클래스 내에서 web.xml에 지정된 속성(예: 초기화 매개변수)에 액세스할 수 있는 방법이 Servlet API에 있습니까?

예를 들어, 저는 Factory 클래스를 작성 중이며, 인스턴스화할 구현 클래스를 결정하는 데 사용할 수 있는 파일과 구성 위치의 계층 구조를 확인하기 위해 Factory 내에 일부 논리를 포함하고 싶습니다. 예를 들어 다음과 같습니다.

  1. 클래스 경로의 속성 파일
  2. web.xml 매개변수,
  3. 시스템 속성 또는
  4. 다른 것이 없는 경우 일부 기본 논리.

나는 다음에 대한 참조를 삽입하지 않고도 이 작업을 수행할 수 있기를 원합니다. ServletConfig 또는 내 공장과 유사한 것 - 코드는 서블릿 컨테이너 외부에서 정상적으로 실행될 수 있어야 합니다.

조금 흔하지 않게 들릴 수도 있지만, 저는 제가 작업하고 있는 이 구성 요소가 웹앱 중 하나와 함께 패키징될 수 있고, 별도의 명령줄 도구와 함께 패키징될 수 있을 만큼 다용도가 되기를 바랍니다. 내 구성 요소에 대해서만 새 속성 파일이 필요하므로 web.xml과 같은 다른 구성 파일 위에 피기백하기를 바랐습니다.

내가 올바르게 기억한다면 .NET에는 다음과 같은 것이 있습니다. Request.GetCurrentRequest() 현재 실행 중인 참조를 얻으려면 Request - 하지만 이것은 Java 앱이기 때문에 다음에 액세스하는 데 사용할 수 있는 비슷한 것을 찾고 있습니다. ServletConfig.

도움이 되었습니까?

해결책

이를 수행할 수 있는 한 가지 방법은 다음과 같습니다.

public class FactoryInitialisingServletContextListener implements ServletContextListener {

    public void contextDestroyed(ServletContextEvent event) {
    }

    public void contextInitialized(ServletContextEvent event) {
        Properties properties = new Properties();
        ServletContext servletContext = event.getServletContext();
        Enumeration<?> keys = servletContext.getInitParameterNames();
        while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();
            String value = servletContext.getInitParameter(key);
            properties.setProperty(key, value);
        }
        Factory.setServletContextProperties(properties);
    }
}

public class Factory {

    static Properties _servletContextProperties = new Properties();

    public static void setServletContextProperties(Properties servletContextProperties) {
        _servletContextProperties = servletContextProperties;
    }
}

그런 다음 web.xml에 다음을 포함하십시오.

<listener>
    <listener-class>com.acme.FactoryInitialisingServletContextListener<listener-class>
</listener>

애플리케이션이 웹 컨테이너에서 실행 중인 경우 컨텍스트가 생성되면 컨테이너에 의해 리스너가 호출됩니다.이 경우 _servletContextProperties는 web.xml에 지정된 context-params로 대체됩니다.

애플리케이션이 웹 컨테이너 외부에서 실행 중인 경우 _servletContextProperties는 비어 있습니다.

다른 팁

이를 위해 Spring 프레임워크 사용을 고려해 보셨나요?이렇게 하면 빈이 추가로 방해받지 않고 Spring이 구성 설정을 처리합니다.

내 생각에는 ServletConfig(또는 ServletContext)에 대한 참조를 취하고 해당 값을 Factory 클래스에 기록하는 관련 부트스트랩 클래스를 추가해야 할 것 같습니다.적어도 이렇게 하면 별도로 포장할 수 있습니다.

@툴킷:탁월함, 가장 겸손함 - 이것은 내가 한동안 시도해 왔던 일입니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top