우선적으로 자주쓰거나 중요한 어노테이션 위주로 정리할 예정이며, 추가적으로 사용하거나 알게되는 어노테이션이 있을 시 지속적으로 추가하여 기록할 예정입니다.

 

 

■ 어노테이션 이란?

 

일반적으로 스프링을 사용하다보면 @ 사인으로 시작하는 부분을 많이 볼 수 있는데, 이러한 것의 이름을 어노테이션 이라고 합니다. 어노테이션이 생기기 전에는 xml로 설정하여 관리 하였으나, 양이 너무 많아지면 관리 및 유지보수가 어려워 지는 단점이 있었습니다. 어노테이션이 생긴 이후부터는 사용과 관리가 매우 쉬워져 요즘은 대부분 어노테이션을 사용하여 개발을 합니다.

 

 

■ 어노테이션 의 종류

 

- @SpringBootApplication

Spring Boot 애플리케이션이 실행시 진입클래스를 가리키에 되는 어노테이션 입니다.

 

ex)

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

 

- @RestController

view가 필요없는 API만을 지원하는 서비스에서 사용합니다. Spring에서 Controller 중 view로 응답하지 않는 Controller를 뜻합니다. 

 

ex)

@RestController
@RequestMapping("/v1/{mallId}/sales")
public class GiftishowRestApi {
  
   private final Logger logger = LoggerFactory.getLogger(getClass());

   @Autowired
   private GiftishowService giftishowService;

 

- @RequestMapping

Spring 컨트롤러의 URI 메소드를 정의하는데 쓰입니다. 요청받는 형식을 GET, POST, PATCH, PUT, DELETE 로 정의 할 수 있으며, 정의하지 않을경우 디폴트로 GET이 정의 됩니다.

 

ex)

@RestController
@RequestMapping("/v1/{mallId}/sales")
@Validated
public class AppInstallRestApi {

   @Autowired
   ApplicationService appService;

   @Autowired
   AppInstallService appInstallService;

   @Autowired
   MemberService memberService;

 

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

각 매핑별로 Get을 예로 들면 위에서 설명한 @RequestMapping(Method=RequestMethod.GET) 와 같습니다.

각각의 형식별로 사용할 수 있습니다.

 

ex)

@GetMapping("/employees")
public List getAllEmployees() {
 return employeeRepository.findAll();
}

 

- @PathVariable

Http의 요청에 대해 매칭되는 request parameter값이 자동으로 매칭됩니다. 

 

ex)

@GetMapping("applications/{OsType}/application/{token}")
public ResponseEntity<?> getAppInstall(@PathVariable final String OsType
       , @PathVariable final String token, final ResponseMapper mapper) {
   AppInstall appInstall = appInstallService.getAppInstallByToken(mallId, token);
   if (appInstall == null) {
       mapper.mapFrom("result",false);
   }else{
       mapper.mapFrom("result",true);
       mapper.mapFrom("marketingAgreeYn", appInstall.getMktgReceiveAgreeYn());
          }
   return ResponseEntity.ok(mapper.getDto());
}

 

- @RequestBody

Http Post 요청에 대해서만 처리되며, Post 요청의 Request body에 있는 request message 의 값을 얻어와 매칭됩니다. 

 

ex)

@PostMapping("applications/application/{token}/agree")
public ResponseEntity<?> updateAppAgree(@RequestBody OpenApiDTO reqDto,
                                       @PathVariable final String mallId, @PathVariable final String token,
                                       final ResponseMapper mapper) {

   if (StringUtils.isBlank(reqDto.getValue("agreeYn", String.class))) {
       throw new BadRequestException("agreeYn must not be empty");
   }

   final AppInstall app = appInstallService.getAppInstallByToken(mallId,token);
   final AgreeYN ag = AgreeYN.valueOf(reqDto.get("agreeYn").toString());
   final Date today = new Date();

   if (app == null) {
       throw new NotFoundException("application not found");
   }

 

- @AutoWired

객체에 대한 의존성을 주입시키며, 해당 어노테이션을 사용할 시 스프링이 자동으로 값을 할당하게 됩니다. 일반적으로 Controller에서 DAO, Service를 주입시킬때 많이 사용합니다.

 

ex)

public class AppInstallRestApi {

   @Autowired
   ApplicationService appService;

   @Autowired
   AppInstallService appInstallService;

   @Autowired
   MemberService memberService;

   @Autowired
   MemberReceiveAgreeRepository repository;

 

- @Service

Service Implement에서 사용되며, 비즈니스 로직을 수행하는 클래스라는 것을 나타내는 용도이다.

 

@Service
@Transactional
public class MemberMyShopServiceImpl implements MemberMyShopService {

   private final Logger logger = LoggerFactory.getLogger(getClass());
  
   /* (non-Javadoc)
    * @see net.g1project.ecp.customer.service.MemberMyShopAService#createMyShopMember(java.lang.Long)
    */
   @Autowired
   private BWJPAQueryFactory factory;

   @Autowired
   private MemberMyshopHistRepository memberMyshopHistRepository;
...

 

 

 

'develop > Spring' 카테고리의 다른 글

Spring 이란? 간단 설명  (0) 2019.10.03

■ Spring 이란?

 

Spring Framework 란 자바 플랫폼을 위한 오픈소스 애플리케이션 프레임워크로서, 동적인 웹사이트를 개발하기 위한 여러가지 서비스는 제공하고 있는 프레임워크 이다. 스프링을 사용하므로써 이미 잘 짜여진 구조 위에서 핵심 로직에만 집중할 수 있어서 높은 생산성과 높은 코드 품질의 좋은 소프트웨어를 개발 할 수 있다.

 

 

■ 애플리케이션 프레임워크 란?

 

애플리케이션 프레임워크는 특정 계층이나 기술, 업무 분야에 국한되지 않은 애플리케이션의 전 영역을 포괄하는 범용적인 프레임워크이다. 애플리케이션 프레임워크는 애플리케이션 개발의 전 과정을 빠르고 편리하며 효율적으로 진행하는데 일차적인 목표를 두는 프레임워크이다. 

 

 

 

 

출처) https://12bme.tistory.com/157

        https://cjh5414.github.io/why-spring/

 

'develop > Spring' 카테고리의 다른 글

Spring @ (어노테이션) 정리  (0) 2019.10.09

+ Recent posts