Spring 프레임워크 및 Spring Boot를 활용한 백엔드 과제 실습 내용을 정리해보았다!
@Transactional과 @Aspect를 활용하여 트랜잭션을 적용@Around를 사용해 메서드 실행 전후에 트랜잭션 시작 및 롤백 처리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;
}
}
@Component가 붙은 클래스가 여러 개일 때, @Primary로 기본 선택 지정 가능@Component
@Primary
public class Dog implements Animal { ... }
@Qualifier("beanName") 사용 시 빈 이름 지정 가능@Component("cat")
public class Cat implements Animal { ... }
@Autowired
@Qualifier("cat")
private Animal animal;
@Value("${key}")를 통해 설정값 주입 가능application.yml에서 key-value 작성 시 tab 대신 space 사용 필수animal:
sound: "야옹"
@Value("${animal.sound}")
private String sound;
@PostConstruct: 빈 초기화 이후 수행할 로직@PreDestroy: 빈 소멸 직전 수행할 로직@PostConstruct
public void init() {
System.out.println("초기화 로직");
}
@PreDestroy
public void cleanup() {
System.out.println("소멸 직전 정리");
}
@Configuration 클래스 내부에서 @Bean 메서드를 통해 수동 등록ApplicationContext로 가져와 사용@Configuration
public class AppConfig {
@Bean
public Dog dog() {
return new Dog();
}
}
Animal 인터페이스 + Dog, Cat 구현체public interface Animal {
void sound();
}
@Autowired
private Animal animal;
@Aspect와 포인트컷 표현식 사용@Before("execution(* com.example..*Service.*(..))")
public void beforeLog(JoinPoint joinPoint) {
System.out.println("메서드 실행 전: " + joinPoint.getSignature());
}
@Bean
@Scope("prototype")
public TestBean prototypeBean() { ... }
@Lazy 사용하여 지연 주입 처리@Autowired
public ClassA(ClassB b) { ... }
@Autowired
public void setClassB(ClassB b) { ... }
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>