WEB 158

Spring Security Fundamentals

SecurityBuilder의 build메소드를 호출하게 되면 필드로 등록된 SecurityConfigure들이 loop를 돌면서 init configue메소드를 내부적으로 호출하면서 초기화가 진행이 된다. 이 과정은 SpringBootApplication.run -> refreshContext 에서 @Configuration으로 등록된 HttpSecurityConfiguration , WebSecurityConfiguration을 통해서 초기화 과정중에 다 자동으로 일어나게 되는일이다. public final class HttpSecurity extends AbstractConfiguredSecurityBuilder implements SecurityBuilder, HttpSecurityBuilder ..

WEB/Security 2022.11.16

운영 이슈 + 아키텍처 테스트

카오스 엔지니어링 툴 프로덕션 환경, 특히 msa에서 불확실성을 파악하고 해결 방안을 모색하는데 사용하는 툴이다. 가령 Controller의 특정 api를 호출 했을때 일부러 응답을 지연시켜서 써킷이 의도한대로 동작을 하는지 테스트할 수 있다. spring.profiles.active=chaos-monkey management.endpoint.chaosmonkey.enabled=true management.endpoints.web.exposure.include=health,info,chaosmonkey chaos.monkey.watcher.repository=true chaos-monkey dependency 를 추가한후에 profile 을 chaos-monkey를 적용시켜줘야한다. spring boot..

WEB/Java Test 2022.11.14

TestContainers

database 랑 연관된 테스트를 진행하고 싶을 때 사용한다. docker container 를 사용하게 되는데 TestContainer는 이를 수동으로 관리하는 번거로움 덜어준다. org.testcontainers junit-jupiter 1.17.2 test org.testcontainers postgresql 1.17.5 test junit 에서 지원하는 testcontainers를 써야한다 spring.datasource.url=jdbc:tc:postgresql:///studytest spring.datasource.driver-class-name=org.testcontainers.jdbc.ContainerDatabaseDriver spring.jpa.hibernate.ddl-auto=creat..

WEB/Java Test 2022.11.11

Mockito

Mock = 진짜 객체와 비슷하게 동작하지만 프로그래머가 직접 그 객체의 행동을 관리하는 객체 Mockito = Mock 객체를 쉽게 만들고 관리하고 검증할 수 있는 방법을 제공, 많이 쓰임 Mock 생성 public StudyService(MemberService memberService, StudyRepository repository) { assert memberService != null; assert repository != null; this.memberService = memberService; this.repository = repository; } test에서 StudyService를 만들어서 써야하지만 MemberService, StudyRepository는 interface만 존재하는..

WEB/Java Test 2022.11.11

JUnit5

Platform = 실제 테스트를 실행해주는 런처 제공 , TestEngine API 제공 Jupiter = JUnit5 를 제공하고 TestEngine API를 구현함 Vintage = JUni3,4 용 TestEngine API 구현체 Spring Boot에서 기본적으로 JUnit5를 디펜던시로 껴있다. 없으면 maven에서 따로 jupiter engine을 추가하면 된다. @BeforeAll , @AfterAll 은 static void로 작성해야하고 전체 테스트 실행 전, 후 실행 되는 메서드이다. @BeforeEach @AfterEach static void로 작성할 필요는 없지만 그냥 통일하는게 좋을듯, 모든 @Test 각각의 전후에 실행되는 메소드이다. @Disabled 는 @Test중에 깨..

WEB/Java Test 2022.11.10

스프링 MVC - 웹 페이지 만들기

PRG (Post Redirect GET) 패턴 상품저장 Controller를 호출하고 바로 상품상세 페이지를 보내준다. 새로고침은 마지막 요청을 다시하는 셈이다. 상품 등록 페이지에서 새로 고침을 할때마다 저장이 된다. 상품저장후 뷰 템플릿으로 이동하는것이 아니라 , 상품 상세 화면으로 리다이렉트를 호출해주면 된다. @PostMapping("/add") public String addItemV4(Item item) { itemRepository.save(item); return "basic/item"; } @PostMapping("/add") public String addItemV6(Item item, RedirectAttributes redirectAttributes) { Item savedItem..

WEB/Spring MVC 1 2022.07.08

스프링 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