728x90

WEB/Spring 29

스프링 DB 2편 1) 스프링 트랜잭션 이해

static class BasicService { @Transactional public void tx() { log.info("call tx"); boolean txActive = TransactionSynchronizationManager.isActualTransactionActive(); log.info("tx active={}", txActive); } public void nonTx() { log.info("call nonTx"); boolean txActive = TransactionSynchronizationManager.isActualTransactionActive(); log.info("tx active={}", txActive); } } 어떤 스레드가 tx,nontx 메소드를 호출했을시..

WEB/Spring 2022.06.20

스프링 DB 1편 4) 스프링과 문제 해결 - 트랜잭션

순수한 서비스 계층 핵심비지니스 로직이 들은 계층임으로 최대한 순수하게 유지해야한다. public void accountTransfer(String fromId, String toId, int money) throws SQLException { Connection con = dataSource.getConnection(); try { con.setAutoCommit(false);//트랜잭션 시작 //비즈니스 로직 bizLogic(con, fromId, toId, money); con.commit(); //성공시 커밋 } catch (Exception e) { con.rollback(); //실패시 롤백 throw new IllegalStateException(e); } finally { release(c..

WEB/Spring 2022.06.16

스프링 핵심 원리 - 고급편 9) 실전, 실무 주의 사항

@Repository public class ExamRepository { private static int seq = 0; /** * 5번에 1번 실패하는 요청 */ @Trace @Retry(value = 4) public String save(String itemId) { seq++; if (seq % 5 == 0) { throw new IllegalStateException("예외 발생"); } return "ok"; } } @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Retry { int value() default 3; } @Aspect public class RetryAspect { @Arou..

WEB/Spring 2022.06.13

스프링 핵심 원리 - 고급편 8) 포인트컷

포인트컷 지시자 execution , within ,args , this , target @target, @within , @annotation , @args , bean 들이 존재한다. @Test void printMethod() { //public java.lang.String hello.aop.member.MemberServiceImpl.hello(java.lang.String) log.info("helloMethod={}", helloMethod); } execution에 썼었던 regexp 같은것이 해당 주석이랑 매핑된다. execution (접근제어자? 반환타입 선언타입?메서드이름(파리미터) 예외? ) ? 는 생략할 수 있다는 의미 접근제어자? == public 반환타입 == java.lang..

WEB/Spring 2022.06.13

스프링 핵심 원리 - 고급편 7) @Aspect AOP , 스프링 AOP 개념

@Aspect AOP AspectJ 에서 제공하는 에노테이션이다. annotation을 차용했을 뿐 실제 내부 구현은 스프링이 한것이다. 진짜 AspectJ를 사용하는것이 아니다. (컴파일 ,로드타임 위버 사용하는것 아님) @Slf4j @Aspect public class LogTraceAspect { private final LogTrace logTrace; public LogTraceAspect(LogTrace logTrace) { this.logTrace = logTrace; } @Around("execution(* hello.proxy.app..*(..))") public Object execute(ProceedingJoinPoint joinPoint) throws Throwable { Trace..

WEB/Spring 2022.06.12

스프링 핵심 원리 - 고급편 6) 빈 후처리기

일반적인 스프링 빈 등록 과정 public class BasicTest { @Test void basicConfig() { ApplicationContext applicationContext = new AnnotationConfigApplicationContext(BasicConfig.class); //A는 빈으로 등록된다. A a = applicationContext.getBean("beanA", A.class); a.helloA(); //B는 빈으로 등록되지 않는다. Assertions.assertThrows(NoSuchBeanDefinitionException.class, () -> applicationContext.getBean(B.class)); } @Slf4j @Configuration sta..

WEB/Spring 2022.06.09

스프링 핵심 원리 - 고급편 5) 스프링이 지원하는 프록시

ProxyFactory 인터페이스가 있을때 -> JDK동적프록시 (InvocationHandler) 인터페이스가 없을때 -> CGLIB(MethodInterceptor) 둘다 구현하기는귀찮다. 특정 조건이 맞을 때 프록시 로직을 적용하는 기능도 공통으로 제공되었으면한다. 추상화 레이어인 ProxyFacotry가 생겼고 InvocationHandler, MethodInterceptor 를 추상화한 Advice가 제공된다. Advice = 조언 , 프록시가 제공하는 부가 기능 로직 Factory안에서 우리가 주입해준 Advice 를 CGLIB,JDK Dynamic을 알아서 구분하여 호출 하게 된다. ProxyFactory + Advice 예제 public class TimeAdvice implements M..

WEB/Spring 2022.06.09

스프링 핵심 원리 - 고급편 4) 동적 프록시 기술

리플렉션 void reflection0() { Hello target = new Hello(); //공통 로직1 시작 log.info("start"); String result1 = target.callA(); //호출하는 메서드가 다음 log.info("result={}", result1); //공통 로직1 종료 //공통 로직2 시작 log.info("start"); String result2 = target.callB(); //호출하는 메서드가 다음 log.info("result={}", result2); //공통 로직2 종료 } 거의 로직1 과 로직 2가 유사하지만 공통 메소드로 묶기가 힘들다. 중간에 호출하는 메서드가 다르기 때문이다. void reflection2() throws Exceptio..

WEB/Spring 2022.06.07

스프링 핵심 원리 - 고급편 4) 프록시 패턴과 데코레이터 패턴

예제 생성할때 주의할점 @Import(AppV1Config.class) @SpringBootApplication(scanBasePackages = "hello.proxy.app") //주의 public class ProxyApplication { 원래는 해당 ProxyApplication이 존재하는 패키지 부터 (proxy) 밑으로 쫘악 component scan을 하지만 여기서는 Configuration을 계속해서 바꾸길 원하기 때문에 basepackage의 위치를 변경하였다. @Configuration public class AppV1Config { @Bean public OrderControllerV1 orderControllerV1() { return new OrderControllerV1Impl..

WEB/Spring 2022.06.06

스프링 핵심원리 고급편 3) 템플릿 메서드 패턴과 콜백 패턴

템플릿 메서드 패턴 부모클래스에 알고리즘의 골격인 template을 정의하고 일부 변경되는 로직은 자식클래스에서 정의하는것이다. 로그 추적기를 사용하는 구조는 모두 동일하다. 이런 boilerplate 를 template으로 만들어서 해결하자 public abstract class AbstractTemplate { public void execute() { long startTime = System.currentTimeMillis(); //비즈니스 로직 실행 call(); //상속 //비즈니스 로직 종료 long endTime = System.currentTimeMillis(); long resultTime = endTime - startTime; log.info("resultTime={}", resul..

WEB/Spring 2022.06.06
728x90