스프링 주요 애너테이션

이정연·2023년 2월 13일
0

spring

목록 보기
3/5

Spring Container

  • 내부에 존재하는 애플리케이션 Bean의 생명주기를 관리한다.
  • ApplicationContext를 스프링 컨테이너라고 하고 인터페이스로 구현되어 있다.
  • 컨테이너는 개발자가 정의한 Bean을 객체로 만들어 관리하고 개발자가 필요로 할 때 제공
  • 객체간의 의존성을 낮추기 위해 Spring 컨테이너가 사용된다.
  • 구현 클래스에 있는 의존을 제거하고 인터페이스에만 의존하도록 설계할 수 있습니다.
  • new AnnotationConfigApplicationContext(구성정보.class)로 스프링에 있는 @Bean의 메서드를 등록한다.
// Spring Container 생성
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(DependencyConfig.class);
// 인스턴스화 하여 이용한다.

@Configuration

  • @Configuration 클래스 자체가 Bean 정의로 등록되고 클래스 내에서 선언된 모든 @Bean 메서드도 Bean 정의로 등록됩니다.
  • 해당 객체가 bean definitions의 소스임을 나타내는 애너테이션입니다.
  • 해당 애너테이션에는 @Component가 적용되어있기 때문에 ComponentScan할 때 자동으로 스프링 빈 등록이 됩니다.
  • 만약 이전 설정 파일 (DependencyConfig 등)에 @Configuration 애너테이션이 붙어있으면 @Configurationr이 설정된 파일 자체를 제거하거나 전체 주석 처리를 해야합니다.
  • 이전 설정 파일(@Configuration이 적용된)을 놔두고 싶다면 ComponentScan의 Filter를 사용할 수도 있습니다.
    @ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Configuration.class))을 추가해줘야합니다.
@Configuration
public class DependencyConfig {
  @Bean
  public MemberService memberService() {
    return new MemberService(memberRepository());
  }
  @Bean
  public MemberRepository memberRepository() {
    return new MemberRepository();
  }
  @Bean
  public CoffeeService coffeeService() {
    return new CoffeeService(coffeeRepository());
  }
  @Bean
  public CoffeeRepository coffeeRepository() {
    return new CoffeeRepository();
  }
}

@Configuration 이 붙은 클래스를 이용하는 방법은 위와 같이 스프링 컨테이너의 파라미터에 넣어 이용한다.
그렇게하면 DependencyConfig안의 Bean들이 모두 등록되어 이용할 수 있다.

@Bean

  • 메서드 레벨 애너테이션
  • 스프링 컨테이너에 의해 관리되는 재사용 소프트웨어 컴포넌트임
  • 스프링 컨테이너에 등록된 객체

@ComponentScan

  • 설정 정보 없이 자동으로 스프링 빈을 등록해준다.
  • @Component가 붙은 모든 클래스를 스프링 빈으로 등록해준다.
@Configuration
@ComponentScan
public class AutoDependencyConfig {

}

해당 코드처럼만 짜놓으면 @ComponentScan이 @Component가 붙은 클래스를 알아서 찾아 적용시킨다.

@AutoWired

  • 생성자 의존성 주입에 필요한 설정 정보 대신 의존관계 자동 주입을 해준다.
  • @Autowired(required=false) : 자동 주입할 대상이 없으면 수정자 메서드 자체가 호출되지 않게 됩니다.
  • @ComponentScan & @Component만 사용했을 때에 DependencyConfig에 어떤 의존 객체를 주입할지 명시해주지 않기 때문에 의존 주입이 필요한 생성자 부분에 @Autowired를 통해 의존 관계 주입이 필요합니다.
  • 대상 빈이 하나의 생성자만 정의하는 경우 @Autowired 지정할 필요가 없습니다.
@Autowired(required = false)
    public void setNoBean1(Member noBean1) {
      System.out.println("noBean1 = " + noBean1);
    }

// 출력결과에는 안나오게됨

@Import

  • 다른 구성 클래스에서 @Bean Definitions를 가져올 수 있습니다.
@Configuration
public class DependencyConfigA {

    @Bean
    public A a() {
        return new A();
    }
}

@Configuration
@Import(DependencyConfigA.class) <------------------------
public class DependencyConfigB {

    @Bean
    public B b() {
        return new B();
    }
}

컨텍스트를 인스턴스화할 때 DependencyConfigA.class와 DependencyConfigB.class 모두 지정하는 대신 DependencyConfigB만 제공하면 된다.

public static void main(String[] args) {
    ApplicationContext ctx = new AnnotationConfigApplicationContext(DependencyConfigB.class);

    // now both beans A and B will be available...
    A a = ctx.getBean(A.class);
    B b = ctx.getBean(B.class);
}
  • 많은 @Configuration 클래스를 기억할 필요 없이 하나의 클래스만 처리하면 됩니다.

@Aspect

  • Spring 설정에서 @AspectJ aspect를 사용하기 위해서는 @AspectJ aspect에 기반한 Spring AOP 설정과 이러한 aspect에 의해 조언되는 자동 프록시 빈에 대한 Spring 지원을 활성화해야 합니다.
  • @Configuration으로 @AspectJ 지원을 활성화하려면 @EnableAspectJAutoProxy 애너테이션을 추가합니다.
@Configuration
@EnableAspectJAutoProxy
public class AppConfig {
}
  • @AspectJ 지원이 활성화되면 @AspectJ 관점(@Aspect 애너테이션이 있음)이 있는 클래스로 애플리케이션 컨텍스트에 정의된 모든 Bean이 Spring에서 자동으로 감지되고 Spring AOP를 구성하는 데 사용됩니다.
profile
반갑습니다.

0개의 댓글