케넨킴
takoyakisoba
케넨킴
글쓰기 / 관리자
전체 방문자
오늘
어제
  • 분류 전체보기 (21)
    • 깨알팁 (2)
    • JAVA (5)
    • JPA (4)
    • Spring (1)
    • 네트워크 (3)
    • 자료구조 (0)
    • TIL (4)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
hELLO · Designed By 정상우.
케넨킴

takoyakisoba

[Spring] application.yml에서 값 가져오기
Spring

[Spring] application.yml에서 값 가져오기

2023. 4. 13. 16:27
greeting:
  message: Welcome to the User Service

첫 번째 방법. Env객체 사용하기

@RestController
@RequestMapping("/")
public class UserController {
    private Environment env;

    @Autowired
    public UserController(Environment env) {
        this.env = env;
    }

    @GetMapping("/welcome")
    public String welcome(){
        return env.getProperty("greeting.message");
    }
}

 

두 번째 방법. @Value 사용하기

우선 클래스를 하나 만들어주고, @Component어노테이션을 추가한다.

package com.example.userservice.vo;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
@Data
public class Greeting {
    @Value("${greeting.message}")
    private String message;
}
//위의 컨트롤러에 추가
@GetMapping("/welcome-annotation")
public String welcomeAnnotation(){
  return greeting.getMessage();
}

 

    케넨킴
    케넨킴
    꾸준히 하는게 젤 어렵더라구요

    티스토리툴바