본문 바로가기

backend/Spring

스프링 프로퍼티 설정 주입2 - @Value를 사용하자


0. @PropertySource로 enviroment꺼내기

  • common.properties
  • properties
@Configuration
@PropertySource("/common.properties")
public class EnvironmentConfig {


    
}

doc에서 PropertySource의 다양한 옵션을 확인하시면 좋을거 같습니다.

@Component
public class PrintOutByEnvironment {
 
    @Autowired
    private Environment env;
 
    @PostConstruct
    private void init(){
        System.out.println(env.getProperty("test.str"));
    }
}

env

  • 위와 같이 Environment에서 test.str를 꺼내서 확인 할 수 있습니다.



그럼 이제 @value를 사용해보자.

1.@PropertyPlaceholderConfigurer를 설정.

@Configuration
public class EnvironmentConfig {

     @Bean
     public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
         return new PropertySourcesPlaceholderConfigurer();
     }
    
}

2. @value를 사용하여 변수에 프로퍼티값 매칭

@Component
public class PrintOutByValue {
 
    @Value("${test.str}")
    private String str;
 
    @PostConstruct
    private void init(){
        System.out.println(str);
    }
}
  • Environment로 접근하지 않고 @value 어노테이션을 이용해서 접근(expression 규칙)
  • SpEL규칙에서 확인 할 수 있듯이 spring에서는 property값에 대하여 list, map, string fucntion 다양한 parsing 기능을 제공하고 있습니다.

@Component를 이용한 커스터마이징

기본적으로 제공하는 다양한 parsing 기능 이외에 커스터마이징을 구현하고 싶을 수 있다.
이럴경우 @Component를 이용하여 본인만의 로직을 만들어서 사용하면 된다.

  • compile(“com.google.guava:guava:18.0”)를 gradle에 추가.(추가하지 않아도 되지만, Splitter를 사용하여 쉽게 파싱하기 위해서 추가)
    env

  • common.properties에 추가된 내용.
    property


CustomValue를 사용

@Component
public class CustomValueUse {
    @Value("#{PropertyMapInListComponent.getMapInList('${cashslide.group}')}")
    private HashMap<String, List<String>> cashslideGroup;
 
    @PostConstruct
    private void init(){
        cashslideGroup.entrySet().stream().forEach(mapItem ->{
            System.out.println("----------------------");
            System.out.println(mapItem.getKey()+" = ");
            mapItem.getValue().stream().forEach(item-> System.out.println(item));
            System.out.println("----------------------");
        });
    }
}


- 위에서는 @Value안에 '$'를 사용하여 프로퍼티 값을 그대로 주입해 주었습니다. 하지만 SpEL을 이용하기 위해서는

'#'를 사용한다.



Custom로직을 구현

@Component("PropertyMapInListComponent")
public class PropertyMapInListComponent {
    public HashMap<String, ArrayList<String>> getMapInList(String data) {
        HashMap<String, ArrayList<String>> result = new HashMap<>();
        Splitter.on("|").omitEmptyStrings().trimResults().withKeyValueSeparator(":").split(data)
                .entrySet().stream().forEach(mapItem -> result.put(mapItem.getKey(), new ArrayList<>(Splitter.on(",").omitEmptyStrings().trimResults().splitToList(mapItem.getValue()))));
        return result;
    }
}
 


결과
result


추가 내용

  • 프로퍼티 값이 한글일 경우 유니코드로 변환후 *.properties에 넣어야 한글이 적용됨:변환제공 사이트

  • 커스터마이징시 주의사항

    ’ , ’ 가 포함된 프로퍼티 값은 기본 parsing에 적용되어 있기 때문에, 커스터마이징하여 parsing을 할 경우 에러를 발생 시킬 수 있습니다.

참고 사이트
https://stackoverflow.com/questions/28369458/how-to-fill-hashmap-from-java-property-file-with-spring-value

github에서 소스코드 확인:https://github.com/ryudung/value-use-springboot