본문 바로가기
개발관련/Spring

Spring에 의해 관리되지 않는 객체, Property 값 주입하기

by joa-yo 2021. 3. 29.
반응형

지금 하려는 작업에서, properties에 정의된 값을 Vo에 정의해주면 매우 작업이 쉽지 않을까? 라는 고민에서부터 이 포스팅은 시작되었다.

 

똑같은 값을 Dao에 주입할 때는 잘 되는데, Vo에는 적용되지 않았다. 왜그럴까 고민을 하다가 Vo는 Spring에서 관리하지 않는 객체라는 결론을 내게 되었다. 그래서 포기하고 있던 찰나! 동료가 열심히 찾아보다가 해결을 해주었는데, 그 방법이 지금 소개하려는 이 방법이다.

 

 

PropertiesLoader는 spring을 활용하지 않고 properties를 읽는 방법이다. 

public class PropertiesLoader {

    public static Properties loadProperties(String resourceFileName) throws IOException {
        Properties configuration = new Properties();
        try {
            InputStream inputStream = PropertiesLoader.class    //properties파일을 읽을 InputStream정의
              .getClassLoader()
              .getResourceAsStream(resourceFileName);
            configuration.load(inputStream);                    //properties파일 읽기
            inputStream.close();                                //InputStream 닫기 (사용 완료 후 꼭 닫아주기)
        } catch(Exception e) {
            e.printStackStrace();
            System.out.println("["+resourceFileName+"]Cannot Read This File");
        }
        return configuration;
    }
}
public class CommonVo {
	String defaultValue = PropertiesLoader.loadProperties("config/file/path").getProperty("commonVo.default.defaultValue");
}

 

PropertiesLoader를 만들고, loadProperties함수를 static하게 정의하여, 파일을 직접 읽어서 Properties내의 값을 받아올 수 있도록 한 모습이다.  이 값을 사용할 때는 CommonVo에 정의한 것 처럼 사용하면 된다.

 

PropertiesLoader.loadProperties([파일경로]).getProperty([propertyKey]);

 

public class StaticValues {
    
    public enum DEFAULT_VAL {
        DEFAULT(PropertiesLoader.loadProperties("config/file/path").getProperty("commonVo.default.defaultValue"))
        
        private defaultVal;
        
        public defaultVal(String defaultVal) {
            defaultVal = defaultVal;
        }
        
        public getDefaultVal() {
            return defaultVal;
        }
    }
}

 

public class CommonVo {
	String defaultValue = DEFAULT_VAL.DEFAULT.getDefaultValue();
}

위와같은 방법은 CommonVo가 생성될 때마다 파일을 읽는다. 매 요청마다 똑같은 파일의 내용을 다시 읽는 것은 매우 비효율 적이다. 이 때문에 Application이 실행될 때, 딱 한번만 값을 읽을 수 있도록 설정한 방법이다. 이전에 만들어두었던 상수들과 동일하게, enum으로 상수값을 선언했다. 이 값을 CommonVo에 넣어줌으로써 효울성을 높일 수 있었다.

 

 

 

 

 

www.baeldung.com/inject-properties-value-non-spring-class

 

How to Inject a Property Value Into a Class Not Managed by Spring? | Baeldung

Learn how to initialize properties values in Java classes without the direct use of Spring's injection mechanism.

www.baeldung.com

 

반응형

댓글