Spring

[Spring] 자주 보는 어노테이션 정리

obin01 2022. 3. 4. 00:32

1. @SpringBootApplication

스프링 부트의 가장 기본적인 설정을 선언

package com.rest.api;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Applications {
    public static void main(String[] args) {
        SpringApplication.run(Applications.class, args);
    }
}

 

2. @Controller

해당 class가 Controller 임을 알려주기 위한 선언 

@ResponseBody + @Controller = @RestController => Json 형태로 객체 데이터를 반환 할때 사용

@Controller
public class TestController {
    ...
}

 

3. @RequestMapping

안에 값으로 url에 매핑한다

method로 지정해서 매핑하는 방법 외에 처음부터 요청방식을 정해놓고 사용하는 방식 4가지 ( Http Method )

-  @GetMapping ,  @PostMapping ,  @PutMapping ,  @DeleteMapping

@RestController
@RequestMapping("api")
public class TestController {
  ...
  // GET Method 통신
  @GetMapping("/getMapping")
  public String getMapping() {
    return "getMapping";
  }
}

 

4. @Service / @Repository

Repository는 DB에 직접 접근 하는 코드들, Service는 Repository를 이용하여 기능구현하는 클래스 임을 명시함

@Service
public class TestService {
	...    
}

 

5. @ControllerAdvice

전역에서 발생할 수 있는 예외를 잡아 처리 ( class형 @ExceptionHandler )

@RestControllerAdvice는 결과값을 Json으로 반환

@ExceptionHandler(Exception.class) 는 예외처리를 해당 handler로 처리하겠다고 명시함

@RestControllerAdvice 
public class TestAdvice { 
  @ExceptionHandler(TestException.class) 
  public String test() { 
    return "test"; 
  } 
}

 

6. @Transactional

선언적 트랜잭션 처리를 지원함

    ( 기본적으로 Unchecked Exception, Error만 롤백하기 때문에 모든 예외처리에 적용시 옵션 사용 )

옵션으로 간단하게 isolation, propagation, noRollbackFor, rollbackFor, timeout, readOnly등이 있다

@Transactional(rollbackFor = {Exception.class}) //특정 예외 발생 시 rollback한다.
public void Test(Object obj) throws Exception {
	...
}

 

7. @PostConstruct

의존성 주입이 이루어진 후 초기화를 수행함 ( 다른 리소스에서 호출되지 않는다해도 수행 )

bean이 초기화됨과 동시에 의존성을 확인 할 수 있고 오직 한번만 수행되어 여러번 초기화 되는것을 방지함

@Service
public class TestServiceImpl implements TestService{
    @Autowired
    TestDAO testDAO;
 
    private TestDTO testDTO;
 
    @PostConstruct
    public void init(){
        testDTO = new TestDTO();
    }
}

 

8. @PropertySource

동적으로 Property 값을 가져오기 위해 사용 ( 환경 세팅 정보 받아오기 )

Enviroment 객체에 getProperty를 통해 값을 받아올수 있다

@Configuration 
@PropertySource("classpath:settings-test.properties")
public class TestConfig{
	
    @Autowired 
    Environment env;
    
    @Bean
    public TestBean testBean(){
    	TestBean testBean = new TestBean();
        testBean,setName(env.getProperty("testbean.name"));
        return testBean;
    }
}

 

9. @Valid

들어오는 객체에 대한 검증을 수행함

세부적인 사항은 객체 안에 정의함

@RestController
public class TestController {

    @PostMapping("/member")
    public ResponseEntity<String> savePost(final @Valid @RequestBody MemberVO memberVO) {
        return ResponseEntity.ok(memberVO);
    }
}

 

10. @Bean/@Component

빈을 등록 할때 사용

Bean은 메소드 수준에서 등록할때 사용하고 Component는 클래스 수준에서 등록할때 사용

@Bean
WebSecurityCustomizer webSecurityCustomizer() {
    return (web) -> web.ignoring().requestMatchers("/css/**", "/js/**", "/images/**");
}

@Component
public class CustomOAuth2FailureHandler implements AuthenticationFailureHandler {
	...
}