코배스 어노테이션 정리

2021. 3. 26. 12:31Spring/Spring[Info]

반응형

Annotation(@) ?

사전적 의미로 주석이라는 뜻이다.

자바에서 Annotation 은 코드 사이에 주석처럼 쓰이며 특별한 의미, 기능을 수행하도록 하는 기술이다.

 

[ 참고 블로그 ]

velog.io/@gillog/Spring-Annotation-%EC%A0%95%EB%A6%AC

 

[Spring] Annotation 정리

Annotation(@)은 사전적 의미로는 주석이라는 뜻이다. 자바에서 사용될 때의 Annotation은 코드 사이에 주석처럼 쓰여서 특별한 의미, 기능을 수행하도록 하는 기술이다.

velog.io


[ Spring Annotation ]

@Componentscan

@Component와 @Service, @Repository, @Controller, @Configuration이 붙은 클래스 Bean들을 찾아서 Context에 bean등록을 해주는 Annotation이다.

ApplicationContext.xml에 <bean id="jaeho" class="jaeho"> 와 같이 xml에 bean을 직접등록하는 방법도 있고 위와 같이 Annotation을 붙여서 하는 방법도 있다.

 

@Component

개발자가 직접 작성한 Class를 Bean으로 등록하기 위한 Annotation

// Bean name : student
@Component
public class Student {
    public Student() {
        System.out.println("hi");
    }
}

// Bean name : mystudent
@Component(value="mystudent")
public class Student {
    public Student() {
        System.out.println("hi");
    }
}

 

추가적인 정보가 없다면 Class의 이름을 camelCase로 변경한 것이 Bean id로 사용된다.

 

@Autowired

속성(field), setter, constructor(생성자)에서 사용하며 Type에 따라 알아서 Bean을 주입 해준다. Type을 먼저 확인 후 찾으면 Name에 따라 주입

 

 

@Controller

Spring의 controller를 의미한다. ( Componentscan의 대상 )

 

@RestController

Spring에서 Controller 중 View로 응답하지 않는, Controller를 의미한다.

method의 반환 결과를 JSON 형태로 반환한다.

이 Annotation이 적혀있는 Controller의 method는 HttpResponse로 바로 응답이 가능하다.

@Controller와 @RestController 의 차이

  • @Controller API와 view를 동시에 사용하는 경우에 사용한다. 대신 API 서비스를 사용하는 경우는 @ResponseBody를 사용하여 객체를 반환한다.
  • @RestController view가 필요없는 API만 지원하는 서비스에서 사용한다. Spring 4.0.1부터 제공 @RequestMapping 메서드가 기본적으로 @ResponseBody 의미를 가정한다. data(json, xml등) return이 주목적이다.

즉, @RestController = @Controller + @ResponseBody 이다.

 

@Service

Service Class에서 쓰인다.

비즈니스 로직을 수행하는 Class라는 것을 나타내는 용도이다.

 

@Repository

DAO Class에서 쓰인다.

DataBase에 접근하는 method를 가지고 있는 class에서 쓰인다.

 

@Configuration

클래스에 적용하고 @Bean을 해당 Class의 method에 적용하면 @Autowired로 Bean을 부를 수 있다.

 

@RequestMapping

요청 URL을 어떤 method가 처리할지 mapping 해주는 annotation이다.

Controller나 Controller의 method에 적용한다.

요청 받는 형식을 정의하지 않는다면, 자동적으로 GET으로 설정된다.

@Controller
// 1) Class Level
//모든 메서드에 적용되는 경우 “/home”로 들어오는 모든 요청에 대한 처리를 해당 클래스에서 한다는 것을 의미
@RequestMapping("/home") 
public class HomeController {
    /* an HTTP GET for /home */ 
    @RequestMapping(method = RequestMethod.GET)
    public String getAllEmployees(Model model) {
        ...
    }
    /*
    2) Handler Level
    요청 url에 대해 해당 메서드에서 처리해야 되는 경우
    “/home/employees” POST 요청에 대한 처리를 addEmployee()에서 한다는 것을 의미한다.
    value: 해당 url로 요청이 들어오면 이 메서드가 수행된다.
    method: 요청 method를 명시한다. 없으면 모든 http method 형식에 대해 수행된다.
    */
    /* an HTTP POST for /home/employees */ 
    @RequestMapping(value = "/employees", method = RequestMethod.POST) 
    public String addEmployee(Employee employee) {
        ...
    }
}

 

@RequestMapping에 대한 모든 매핑 정보는 Spring에서 제공하는 HandlerMapping Class가 가지고 있다.

 

@ModelAttribute

view에서 전달해주는 parameter를 Class(VO/DTO)의 멤버 변수로 binding 해주는 Annotation이다.

binding 기준은 <input name="id" /> 처럼 어떤 태그의 name값이 해당 Class의 멤버 변수명과 일치해야하고 setmethod명도 일치해야한다.

class Person {

String id;

public void setId(String id){ this.id = id;}
public String getId(){ return this.id }
}

@Controller
@RequestMapping("/person/*")
public class PersonController{
	//view에서 myMEM으로 던져준 데이터에 담긴 id 변수를 Person타입의 person이라는 객체명으로 바인딩.
	@RequestMapping(value = "/info", method=RequestMethod.GET)
	public void show(@ModelAttribute("myMEM") Person person, Model model)
	{ model.addAttribute(service.read(person.getId())); }
}

 

 

@GetMapping

@RequestMapping(Method=RequestMethod.GET)과 같다.

@PostMapping, @PutMapping, @PatchMapping, @DeleteMapping 등 도 있다.

 

@SessionAttributes

Session에 data를 넣을 때 쓰는 Annotation이다.

@SessionAttributes("name")이라고 하면 Model에 key값이 "name"으로 있는 값은 자동으로 세션에도 저장되게 한다.

 

@RequestAttribute

Request에 설정되어 있는 속성 값을 가져올 수 있다.

 

@RequestBody

요청이 온 데이터(JSON이나 XML형식)를 바로 Class나 model로 매핑하기 위한 Annotation이다.

POST나 PUT, PATCH로 요청을 받을때에, 요청에서 넘어온 body 값들을 자바 타입으로 파싱해준다.

HTTP POST 요청에 대해 request body에 있는 request message에서 값을 얻어와 매핑한다.

RequestData를 바로 Model이나 클래스로 매칭한다.

이를테면 JSON 이나 XML같은 데이터를 적절한 messageConverter로 읽을 때 사용하거나 POJO 형태의 데이터 전체로 받는 경우에 사용한다.

@RequestMapping(value = "/book", method = RequestMethod.POST)
public ResponseEntity<?> someMethod(@RequestBody Book book) {
// we can use the variable named book which has Book model type.
try {
   service.insertBook(book);
} catch(Exception e) {
    e.printStackTrace();
}

// return some response here
}

 

 

@RequestHeader

Request의 header값을 가져올 수 있다. 메소드의 파라미터에 사용한다.

//ko-KR,ko;q=0.8,en-US;q=0.6
@RequestHeader(value="Accept-Language")String acceptLanguage 로 사용

 

 

@RequestParam

@PathVariable과 비슷하다. request의 parameter에서 가져오는 것이다.

method의 파라미터에 사용된다. ?moviename=thepurge 와 같은 쿼리 파라미터를 파싱해준다.

HTTP GET 요청에 대해 매칭되는 request parameter 값이 자동으로 들어간다. url 뒤에 붙는 parameter 값을 가져올 때 사용한다.

// http://localhost:8080/home?index=1&page=2 (주소값)
@GetMapping("/home")
public String show(@RequestParam("page") int pageNum {
}

 

@ResponseBody

HttpMessageConverter를 이용하여 JSON 혹은 xml 로 요청에 응답할수 있게 해주는 Annotation이다.

 

view가 아닌 JSON 형식의 값을 응답할 때 사용하는 Annotation으로 문자열을 리턴하면 그 값을 http response header가 아닌 response body에 들어간다.

이미 RestController Annotation이 붙어 있다면, 쓸 필요가 없다. 허나 그렇지 않은 단순 컨트롤러라면, HttpResponse로 응답 할 수 있게 해준다.

만약 객체를 return하는 경우 JACKSON 라이브러리에 의해 문자열로 변환되어 전송된다.

context에 설정된 viewResolver를 무시한다고 보면된다.

 

@PathVariable

method parameter 앞에 사용하면서 해당 URL에서 {특정값}을 변수로 받아 올 수 있다.

@RequestMapping(value = "/some/path/{id}", method = RequestMethod.GET)
public ResponseEntity<?> someMethod(@PathVariable int id) {
}

 

 

HTTP 요청에 대해 매핑되는 request parameter 값이 자동으로 Binding 된다.

uri에서 각 구분자에 들어오는 값을 처리해야 할 때 사용한다.

REST API에서 값을 호출할 때 주로 많이 사용한다.

// http://localhost:8080/index/1
@PostMapping("/index/{idx}")
@ResponseBody
public boolean deletePost(@PathVariable("idx") int postNum) {
return postService.deletePost(postNum);
}

 

@RequestParam와 @PathVariable 동시 사용 예제

@GetMapping("/user/{userId}/invoices")
public List<Invoice> listUsersInvoices(@PathVariable("userId") int user,
                      @RequestParam(value = "date", required = false) Date dateOrNull) {
}

 

위의 경우 GET /user/{userId}/invoices?date=190101 와 같이 uri가 전달될 때 구분자 {userId}는@PathVariable(“userId”)로,뒤에 이어붙은 parameter 는 @RequestParam(“date”) 로 받아온다.


[ Lombok Annotation ]

@NoArgsConstructor

기본생성자를 자동으로 추가한다.

@NoArgsConstructor(access = AccessLevel.PROTECTED)

기본생성자의 접근 권한을 protected로 제한한다.

Entity Class를 프로젝트 코드상에서 기본생성자로 생성하는 것은 금지하고, JPA에서 Entity 클래스를 생성하는것은 허용하기 위해 추가한다.

 

@AllArgsConstructor

모든 필드 값을 파라미터로 받는 생성자를 추가한다.

 

@Getter

Class 내 모든 필드의 Getter method를 자동 생성한다.

 

@Setter

Class 내 모든 필드의 Setter method를 자동 생성한다.

Controller에서 @RequestBody로 외부에서 데이터를 받는 경우엔 기본생성자 + set method를 통해서만 값이 할당된다. 그래서 이때만 setter를 허용한다. Entity Class에는 Setter를 설정하면 안된다.

차라리 DTO 클래스를 생성해서 DTO 타입으로 받도록 하자

 

@ToString

Class 내 모든 필드의 toString method를 자동 생성한다.

@ToString(exclude = "password")특정 필드를 toString() 결과에서 제외한다. 클래스명(필드1이름=필드1값, 필드2이름=필드2값, …) 식으로 출력된다.

 

@Data

@Getter @Setter @EqualsAndHashCode @AllArgsConstructor을 포함한 Lombok에서 제공하는 필드와 관련된 모든 코드를 생성한다.

실제로 사용하지 않는것이 좋다. 전체적인 모든 기능 허용으로 위험 존재

반응형