@Bean和@Autowired之间的区别 [英] Difference between @Bean and @Autowired

查看:121
本文介绍了@Bean和@Autowired之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能在这种情况下使用 @Autowired

Why can't I use @Autowired in this case?

@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 同样的事情?

Aren't the two ways to generate BookingService the same thing?

推荐答案

@Bean @Autowired 做两件完全不同的事情。这里的其他答案更详细地解释,但更简单:

@Bean and @Autowired do two very different things. The other answers here explain in a little more detail, but at a simpler level:


  • @Bean 告诉Spring'这是这个类的一个实例,请保留它并在我询问时将它还给我。

  • @Bean tells Spring 'here is an instance of this class, please keep hold of it and give it back to me when I ask'.

@Autowired 说'请给我一个这个类的实例,例如,我用 @Bean 之前的注释'。

@Autowired says 'please give me an instance of this class, for example, one that I created with an @Bean annotation earlier'.

这有意义吗?在你的第一个例子中,你要求Spring给你一个 BookingService 的实例,但你永远不会创建一个,所以Spring没有什么可以给你。在你的第二个例子中,你正在创建一个新的 BookingService 实例,告诉Spring它,然后在 main()方法,要求退回。

Does that make sense? In your first example, you're asking Spring to give you an instance of BookingService, but you're never creating one, so Spring has nothing to give you. In your second example, you're creating a new instance of BookingService, telling Spring about it, and then, in the main() method, asking for it back.

如果需要,可以从第二个 main()<中删除另外两行/ code>方法,并结合您的两个示例如下:

If you wanted, you could remove the two additional lines from the second main() method, and combine your two examples as below:

@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 使用它。

In this case, the @Bean annotation gives Spring the BookingService, and the @Autowired makes use of it.

这将是一个毫无意义的例子,因为你在同一个类中使用它,但如果你有 @它会变得很有用Bean 在一个类中定义, @Autowired 在另一个类中定义。

This would be a slightly pointless example, as you're using it all in the same class, but it becomes useful if you have the @Bean defined in one class, and the @Autowired in a different one.

这篇关于@Bean和@Autowired之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆