과제 정리] 구름 부트캠프 백엔드 3회차 - java 기초

권재은·2025년 4월 20일

Spring 프레임워크 & Spring Boot 과제 정리 (1번 ~ 12번)

Spring 프레임워크 및 Spring Boot를 활용한 백엔드 과제 실습 내용을 정리해보았다!


1. AOP 기반 트랜잭션 제어

  • @Transactional@Aspect를 활용하여 트랜잭션을 적용
  • @Around를 사용해 메서드 실행 전후에 트랜잭션 시작 및 롤백 처리
  • H2 임베디드 DB 사용 (spring-boot-starter-jdbc 의존성 필요)
@Around("@annotation(org.springframework.transaction.annotation.Transactional)")
public Object logTransaction(ProceedingJoinPoint joinPoint) throws Throwable {
    try {
        System.out.println("트랜잭션 시작: " + joinPoint.getSignature());
        Object result = joinPoint.proceed();
        System.out.println("트랜잭션 커밋");
        return result;
    } catch (Exception e) {
        System.out.println("트랜잭션 롤백");
        throw e;
    }
}

2. @Primary를 활용한 동일 타입 빈 우선 지정

  • @Component가 붙은 클래스가 여러 개일 때, @Primary로 기본 선택 지정 가능
  • 하나의 빈만 주입할 경우 Spring이 자동 주입 대상 선택
@Component
@Primary
public class Dog implements Animal { ... }

3. @Qualifier를 활용한 특정 빈 선택

  • 동일한 타입의 여러 빈 중 명시적으로 선택할 경우 사용
  • @Qualifier("beanName") 사용 시 빈 이름 지정 가능
@Component("cat")
public class Cat implements Animal { ... }

@Autowired
@Qualifier("cat")
private Animal animal;

4. application.yml 또는 .properties 설정 주입

  • @Value("${key}")를 통해 설정값 주입 가능
  • application.yml에서 key-value 작성 시 tab 대신 space 사용 필수
animal:
  sound: "야옹"
@Value("${animal.sound}")
private String sound;

5. 빈 생명주기 제어 (@PostConstruct, @PreDestroy)

  • @PostConstruct: 빈 초기화 이후 수행할 로직
  • @PreDestroy: 빈 소멸 직전 수행할 로직
@PostConstruct
public void init() {
    System.out.println("초기화 로직");
}

@PreDestroy
public void cleanup() {
    System.out.println("소멸 직전 정리");
}

6. JavaConfig 기반 빈 등록

  • @Configuration 클래스 내부에서 @Bean 메서드를 통해 수동 등록
  • ApplicationContext로 가져와 사용
@Configuration
public class AppConfig {
    @Bean
    public Dog dog() {
        return new Dog();
    }
}

7. 인터페이스 기반 의존성 주입

  • 구현체를 추상화하여 느슨한 결합 구조 설계
  • Animal 인터페이스 + Dog, Cat 구현체
public interface Animal {
    void sound();
}
@Autowired
private Animal animal;

8. AOP 애스펙트 구현 (일반 로깅 등)

  • 로깅이나 보안 체크 등 공통 관심사를 모듈화
  • @Aspect와 포인트컷 표현식 사용
@Before("execution(* com.example..*Service.*(..))")
public void beforeLog(JoinPoint joinPoint) {
    System.out.println("메서드 실행 전: " + joinPoint.getSignature());
}

9. 빈 스코프 비교 (singleton vs prototype)

  • singleton: 한 번 생성 후 동일 인스턴스 반환
  • prototype: 요청 시마다 새로운 인스턴스 반환
@Bean
@Scope("prototype")
public TestBean prototypeBean() { ... }

10. 순환 의존성 문제 해결

  • 필드 주입 시 순환 의존 발생 가능
  • 해결 방법:
    • 생성자 → setter 방식으로 변경
    • @Lazy 사용하여 지연 주입 처리

11. 애너테이션 기반 주입 (@Autowired)

  • 필드, setter, 생성자 주입 모두 가능
  • 생성자 주입 시 생성자가 하나면 생략 가능
@Autowired
public ClassA(ClassB b) { ... }

@Autowired
public void setClassB(ClassB b) { ... }

12. XML 기반 빈 등록 및 의존성 주입

  • applicationContext.xml을 통해 Bean 정의
  • setXxx(...) 방식의 setter 주입 필요
<bean id="printer" class="com.example.Printer"/>
<bean id="helloService" class="com.example.HelloService">
    <property name="printer" ref="printer"/>
</bean>
profile
코딩천재 꿈나무

0개의 댓글