1 minute read

개요

로드 시점에 초기화가 필요한 것
💡 아래와 유형은 미리 초기화.
💡 LDAP API
💡 OTP API
💡 등등….

구현

SampleContextEventListener.java

public class SampleContextEventListener implements ServletContextListener {
    
    private static final Logger logger = LoggerFactory.getLogger("org.wso2.sample.is.sso.agent");

    public void contextInitialized(ServletContextEvent servletContextEvent) {

        properties = new Properties();
        try {
            String resourcePath = "/WEB-INF/classes" + servletContextEvent.getServletContext().getContextPath() + "/wso2.properties";

            inputStream resourceStream = servletContextEvent.getServletContext().getResourceAsStream(resourcePath);

            if(resourceStream != null) 
            {
                properties.load(servletContextEvent.getResourceAsStream(resourcePath));
            }

            InputStream keyStoreInputStream = servletContextEvent.getServletContext().getResourceAsStream("/WEB-INF/classes/wso2carbon.jks");

            SSOAgentX509Credential credential = new SSOAgentX509KeyStoreCredential(ketStoreInputStream, 
            properties.getProperty("KeyStorePassword");
            properties.getProperty("IdPPublicCertAlias");
            properties.getProperty("PrivateKeyAlias");
            properties.getProperty("PrivateKeyPassword").toCharArray());

            SSOAgentConfig config = new SSOAgentConfig();
            config.initConfig(properties);
            config.getSAML2().setSSOAgentX509Credential(credential);
            config.getOpenId().setAttributesRequestor(new SampleAttributesRequestor());
            servletContextEvent.getServletContext().setAttribute(SSOAgentConstants.CONFIG_BEAN_NAME, config);

        } catch (IOException e) {

        } catch (SSOAgentException e) {

        } 
        

        public static Properties getProperties() {
            return properties;
        }
    }
}

ServletContextListener 구현체 클래스파일 생성
💡 implements ServletContextListener
💡 이 클래스파일이 초기에 빈에 등록되어 실행되도록 한다.

web.xml

<web-app>
    <!-- 중략 -->
    <listener>
        <listener-class>com.example.SampleContextEventListener</listener-class>
    </listener>
</web-app>

정리

SampleContextEventListener 클래스에서 초기화된 전역 필드인 private static Properties properties; 객체는 해당 클래스가 로드되고 초기화된 이후 어디에서나 사용할 수 있다.

전역 필드가 private static으로 선언되었으므로 클래스 내부에서만 접근할 수 있다. 그러나 해당 클래스의 메서드나 다른 클래스에서 SampleContextEventListener.getProperties() 와 같이 d접근할 수 있다.

또한, Properties 객체가 스태틱으로 선언되었기 때문에 애플리케이션 전체에서 공유될 수 있습니다. 따라서 MyServletContextListener 클래스의 초기화 메서드에서 한 번 초기화되면 다른 클래스나 컴포넌트에서 해당 객체에 접근하여 데이터를 읽거나 수정할 수 있다.

전역 필드가 static으로 선언되었기 때문에 해당 클래스의 인스턴스를 생성하지 않고도 접근할 수 있으며, properties 객체는 스태틱으로 선언되어 있으므로 애플리케이션의 생명 주기 동안 메모리에 상주한다.

Leave a comment