일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- jpqlquery
- embededtype
- JDBC connection pool
- gitinitial
- JPA프록시
- dockercmd
- JPA Hint & Lock
- springbootH2
- Git
- JPA값타입
- sql
- JPAproxy
- 데이터베이트h2
- spring
- 제이피큐엘쿼리
- httppie
- 스프링부트
- 스프링부트기본설정
- Open EntityManager
- springbootproxy
- javageneric
- 임베디드타입
- OSIV
- jpa
- springboot기본설정
- 이해와 원리
- JPAmapping
- MySqlType
- 에이치투데이터베이스
- 자바제너릭
Archives
- Today
- Total
빡코
[개념] AOP(관점지향프로그래밍) 본문
AOP 소개
흩어진 코드를 한 곳으로 모아
예제
>>public @interface LogExecutionTime 생성
package org.springframework.samples.petclinic.aspect;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD) //메소드에다가 붙일거니까 타켓이 메소드
@Retention(RetentionPolicy.RUNTIME) //어노테이션을 사용한이 코드를 언제까지 유지할거냐
public @interface LogExecutionTime {
}
>>public class LogAspect 생성
package org.springframework.samples.petclinic.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
@Component //Spring bean만 Aspect가 될 수 있다
@Aspect
public class LogAspect {
Logger logger = LoggerFactory.getLogger(LogAspect.class);
//이 어노테이션주변으로 이런일들을 하라
@Around("@annotaion(LogExecutionTime)")
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable{
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Object proceed = joinPoint.proceed();
stopWatch.stop();
logger.info(stopWatch.prettyPrint());
return proceed;
}
}
>>아래와 같이 적용
@Controller
class OwnerController {
private static final String VIEWS_OWNER_CREATE_OR_UPDATE_FORM = "owners/createOrUpdateOwnerForm";
private final OwnerRepository owners;
private VisitRepository visits;
public OwnerController(OwnerRepository clinicService, VisitRepository visits) {
this.owners = clinicService;
this.visits = visits;
}
@InitBinder
public void setAllowedFields(WebDataBinder dataBinder) {
dataBinder.setDisallowedFields("id");
}
@LogExecutionTime
@GetMapping("/owners/new")
public String initCreationForm(Map<String, Object> model) {
Owner owner = new Owner();
model.put("owner", owner);
return VIEWS_OWNER_CREATE_OR_UPDATE_FORM;
}
@LogExecutionTime
@PostMapping("/owners/new")
public String processCreationForm(@Valid Owner owner, BindingResult result) {
if (result.hasErrors()) {
return VIEWS_OWNER_CREATE_OR_UPDATE_FORM;
}
else {
this.owners.save(owner);
return "redirect:/owners/" + owner.getId();
}
}
@LogExecutionTime
@GetMapping("/owners/find")
public String initFindForm(Map<String, Object> model) {
model.put("owner", new Owner());
return "owners/findOwners";
}
@LogExecutionTime
@GetMapping("/owners")
public String processFindForm(Owner owner, BindingResult result, Map<String, Object> model) {
// allow parameterless GET request for /owners to return all records
if (owner.getLastName() == null) {
owner.setLastName(""); // empty string signifies broadest possible search
}
// find owners by last name
Collection<Owner> results = this.owners.findByLastName(owner.getLastName());
if (results.isEmpty()) {
// no owners found
result.rejectValue("lastName", "notFound", "not found");
return "owners/findOwners";
}
else if (results.size() == 1) {
// 1 owner found
owner = results.iterator().next();
return "redirect:/owners/" + owner.getId();
}
else {
// multiple owners found
model.put("selections", results);
return "owners/ownersList";
}
}
@GetMapping("/owners/{ownerId}/edit")
public String initUpdateOwnerForm(@PathVariable("ownerId") int ownerId, Model model) {
Owner owner = this.owners.findById(ownerId);
model.addAttribute(owner);
return VIEWS_OWNER_CREATE_OR_UPDATE_FORM;
}
@PostMapping("/owners/{ownerId}/edit")
public String processUpdateOwnerForm(@Valid Owner owner, BindingResult result,
@PathVariable("ownerId") int ownerId) {
if (result.hasErrors()) {
return VIEWS_OWNER_CREATE_OR_UPDATE_FORM;
}
else {
owner.setId(ownerId);
this.owners.save(owner);
return "redirect:/owners/{ownerId}";
}
}
@GetMapping("/owners/{ownerId}")
public ModelAndView showOwner(@PathVariable("ownerId") int ownerId) {
ModelAndView mav = new ModelAndView("owners/ownerDetails");
Owner owner = this.owners.findById(ownerId);
for (Pet pet : owner.getPets()) {
pet.setVisitsInternal(visits.findByPetId(pet.getId()));
}
mav.addObject(owner);
return mav;
}
}
구조
출력되는 결과
참조
https://drive.google.com/file/d/1Q8LGrUKzV_EX6MToQaynhv0CnPDCTgbM/view
'Java > Spring Framework' 카테고리의 다른 글
리플렉션 API 개념 및 실습 (0) | 2024.01.15 |
---|---|
[Spring] 기본개념 (0) | 2023.01.20 |
[개념] MVC 패턴_데이터의 흐름 (0) | 2020.01.29 |
[개념] Maven_기본개념 (0) | 2020.01.27 |
[개념] 제어의 역전(IoC) + 의존성주입(DI) (0) | 2020.01.25 |