JAVA 공부/스프링부트

Spring boot 어노테이션

krbnf 2025. 1. 27. 15:36
반응형

1.@Restcontroller - 특정 주소에 대해서 상호작용(요청/응답)할 수 있는 도구 

  @Controller 와 @ ResponseBody 가 합쳐진 어노테이션이지만 json 같은 반환만 가능하다 

 

  @Controller처럼  return /WEB-INF/views/ list.jsp 같이 jsp 로 보내는건 불가능

 

2.@RequestMapping("???") - 원하는 주소를 지정하는 도구다 

   ex) @RequestMapping("/home")

 

3.@RequestParam -요청 파라미터 

public String plus(@RequestParam int left, @RequestParam int right){
    int total = left + right;
    return "덧셈 결과 " + total;
}

 

여기서 @RequestParam 요청 파라미터 즉 요청 URL에서 left=5와 right=3이 전달되면, 이 값들이 각각 left와 right 변수에 할당된다. 보통은 생략 가능하지만 잊어버릴 수 있으니 생략은 권하지 않는다.

 

public String plus(@RequestParam(required=false,defaultValue="0") int left, @RequestParam int right){
    int total = left + right;
    return "덧셈 결과 " + total;
}

이렇게  @RequestParam 에 ()를 열고 필수 여부와 디폴트 값 설정을 해줄 수 있다.

 

 

4.@Autowired-의존성 주입

public class MyService {
    private MyRepository myRepository;

    public MyService() {
        // 직접 의존성을 만들어야 합니다.
        this.myRepository = new MyRepository();
    }
    
    public void doSomething() {
        myRepository.save();
    }
}

@Autowired 없이 코드작성

 

 

@Service
public class MyService {
    @Autowired
    private MyRepository myRepository;  // Spring이 자동으로 주입

    public void doSomething() {
        myRepository.save();  // 의존성을 자동으로 주입받아서 사용
    }
}

@Component
public class MyRepository {
    public void save() {
        System.out.println("데이터 저장");
    }
}

@Autowired 사용한 코드작성

 

 

@ResponseBody-HTTP의 BODY에 문자 내용을 직접 반환 ( JSON형식 key-value)

  HTTP에는 헤더와 바디 부분이 있음 

반응형

'JAVA 공부 > 스프링부트' 카테고리의 다른 글

스프링(spring)에서 jdbc 사용하기  (0) 2025.01.27
kh15 spring boot 시작(초기설정)  (0) 2025.01.27