DOMDOM
0posts
today
total
personal posts · since 2021

Fragments
of a day.

A small notebook for slow moments slipping by.

2023 IT Creator
2024 Food Creator
2025 News Creator
2026 News Creator

Latest Posts최근

tistory view

Back to Home

config.properties value를 static method에서 가져와서 사용하기

728x90
반응형

 

config.properties에 프로퍼티를 설정해놓고 
아래처럼 클래스에서 @Value로 불러와서 사용하려고하니
System.out.println(settings) 에서 null이 출력되었습니다.

public class test {
    @Value("#{property['settings']}")
    private String settings;

    public static String startSetting(...) {
        System.out.println(settings);
        if ("A".equals(settings)){
            ...
        }else if ("B".equals(settings)){
            ...
        }
    }
}



일단 요 클래스가 Spring Bean이 아니기에 @Autowired와 @Value는 사용할 수 없어
@Component를 추가해 Spring Bean으로 등록해주었고
(@Autowired, @Value 사용 가능)

@Component 추가로 인한
기존 메서드나 필드에는 영향 없어 기존 코드 그대로 사용이 가능합니다.

하지만 정적(static) 메서드는 그대로 작동하지만, @Value는 static 필드에는 적용되지 않습니다.
Setter를 사용하여 static 변수에 값을 넣어주면
이제 System.out.println(settings) 에서 config.properties에 입력한 settings의 값이 출력됩니다.

@Component
public class test {
    private static String settings;

    @Value("#{property['settings']}")
    public void setsettings(String settings) {
        test.settings = settings;
    }

    public static String startSetting(...) {
        System.out.println(settings);
        if ("A".equals(settings)){
            ...
        }else if ("B".equals(settings)){
            ...
        }
    }
}

 

728x90
반응형

Comments

Thanks for staying up late.

keep wandering · keep listening