IT story

@Bean과 @Autowired의 차이점

hot-time 2021. 1. 5. 19:15
반응형

@Bean과 @Autowired의 차이점


@Autowired이 경우 왜 사용할 수 없습니까?

@SpringBootApplication
public class Application {

    @Autowired
    BookingService bookingService;

    public static void main(String[] args) {
        bookingService.book("Alice", "Bob", "Carol");
    }
}

하지만 사용할 수 있습니다 @Bean

@SpringBootApplication
public class Application {

    @Bean
    BookingService bookingService() {
        return new BookingService();
    }

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);
        BookingService bookingService = ctx.getBean(BookingService.class);
        bookingService.book("Alice", "Bob", "Carol");
    }
}

BookingService동일한 것을 생성하는 두 가지 방법이 아닌가요?


@Bean그리고 @Autowired두 개의 매우 다른 일을. 여기의 다른 답변은 조금 더 자세히 설명하지만 더 간단한 수준으로 설명합니다.

  • @Bean Spring에 '여기에이 클래스의 인스턴스가 있습니다. 잠시만 기다려주세요. 내가 물어 보면 다시 돌려주세요'라고 말합니다.

  • @Autowired'이 클래스의 인스턴스 (예 : @Bean이전 주석으로 만든 클래스)를주세요'라고 말합니다 .

말이 돼? 첫 번째 예에서 Spring에의 인스턴스를 제공하도록 요청 BookingService하지만 인스턴스를 생성하지 않으므로 Spring은 제공 할 것이 없습니다. 두 번째 예제에서는의 새 인스턴스를 만들고 BookingServiceSpring에 대해 알리고 main()메서드에서 다시 요청합니다.

원하는 경우 두 번째 main()방법 에서 두 줄을 추가로 제거하고 다음과 같이 두 예제를 결합 할 수 있습니다.

@SpringBootApplication
public class Application {

  @Autowired
  BookingService bookingService;

  @Bean
  BookingService bookingService() {
    return new BookingService();
  }

  public static void main(String[] args) {
    bookingService.book("Alice", "Bob", "Carol");
  }
}

이 경우 @Bean주석은 Spring에을 제공 BookingService하고 @Autowired이를 사용합니다.

이것은 같은 클래스에서 모두 사용하기 때문에 약간 무의미한 예이지만 @Bean한 클래스와 다른 클래스 에서 정의 된 경우 유용합니다 @Autowired.


@Bean
BookingService bookingService() {
    return new BookingService();
}

Annotating @Bean only registers the service as a bean(kind of an Object) in spring application context. In simple words, it is just registration and nothing else.

@Autowired
BookingService bookingService;

Annotating a variable with @Autowired injects a BookingService bean(i.e Object) from Spring Application Context.

(i.e) The registered bean with @Bean annotation will be injected to the variable annotated with @Autowired.

Hope this clears your doubt!


great answer by @DaveyDaveDave In the example instead of

@Bean
  BookingService bookingService() {
    return new BookingService();
  }

You can use @Service annotation on BookingService class


Here's good article about @Autowired annotation: http://www.baeldung.com/spring-autowire

The @Autowired annotation can instantiate your injectables by defining @ComponentScan("namespace.with.your.components.for.inject") on config class

@Configuration
@ComponentScan("com.baeldung.autowire.sample")
public class AppConfig {}

All components must be marked by @Component annotation. It replaces the @Bean annotation.


@Bean is just for the metadata definition to create the bean(equivalent to tag). @Autowired is to inject the dependancy into a bean(equivalent to ref XML tag/attribute).

ReferenceURL : https://stackoverflow.com/questions/34172888/difference-between-bean-and-autowired

반응형