[Spring] 다양한 스프링 어노테이션

FeelingXD·2023년 8월 1일
1

Spring

목록 보기
1/1
post-thumbnail

스프링 어노테이션들에 대한 간소화된 버전의 설명을 작성합니다.

@Configuration


@Bean 등록에 사용되는 어노테이션 @Configuration 을 사용하지않아도 Bean등록은 가능하지만 @Configuration 에서 @Bean을 등록한다면 등록된 @Bean들이 싱글톤임이 보장된다.

스프링 컨테이너가 @Configuration 이 붙어있는 클래스를 자동으로 빈으로 등록한 이후 @Bean 어노테이션이 붙어있는 메소드를 찾아 빈으로 생성한다.

@Bean


위의 @Configuration을 통해 수동으로 Bean을 등록하는 경우는 다음과같다.

  • 개발자가 제어할수없는 코드를 사용할때 ( 외부 라이브러리 등 프로젝트 외부코드 )
  • 여러 구현체를 사용할경우 (다형성)
  • 애플리케이션 전범위적으로 사용되는 클래스를 등록할 때
  • 추가적으로 @Bean을 사용해서 등록시 메서드명으로 빈이 등록된다.
// 외부라이브러리를 사용하는경우
@Configuration
public class QuerydslConfiguration {

  @PersistenceContext
  private EntityManager entityManager;

  @Bean
  public JPAQueryFactory jpaQueryFactory() {
    return new JPAQueryFactory(entityManager);
  }

}
//다형성의경우 
@Bean
  public RedisTemplate<String, String> redisSignTemplate() {
    RedisTemplate<String, String> template = new RedisTemplate<>();
    template.setValueSerializer(new StringRedisSerializer());
    template.setKeySerializer(new StringRedisSerializer());
    template.setConnectionFactory(lettuceConnectionFactory());
    return template;
  }
  @Bean
  public  RedisTemplate<String,Object> redisCacheTemplate() {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    template.setKeySerializer(new StringRedisSerializer());
    template.setConnectionFactory(lettuceConnectionFactory());
    return template;
  }

@Component


직접 작성한 클래스를 등록할때 사용하는 @Component 물론 @Bean으로도 등록가능하지만 스프링은 Component Scan을 통해 @Component 어노테이션을 검사하고 자동으로 빈등록을 해서 관리해준다.

//Example
// 직접만든 클래스 를 사용할때 @Component 어노테이션으로 자동등록을 유도한다.
@Component
@Aspect
@Slf4j
public class LoggingAspect {

  @Before("@annotation(com.example.global.config.aop.logger.CustomLogger)")
  public void logBeforeExecution(JoinPoint joinPoint){
    log.warn("start :"+ System.currentTimeMillis());
  }
  @After("@annotation(com.example.global.config.aop.logger.CustomLogger)")
  public void logAfterExecution(JoinPoint joinPoint){
    log.warn("end :"+ System.currentTimeMillis());
  }

}
profile
tistory로 이사갑니다. :) https://feelingxd.tistory.com/

0개의 댓글