Java – @ bean is different from @ Autowired
•
Java
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");
}
}
@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","Carol");
}
}
Solution
@Bean and @ Autowired do two very different things Other answers are explained in more detail here, but at a simpler level: @ h_ 404_ 4 @ > @ bean tells spring that this is an instance of this class. Please keep it and give it back when I ask '
@SpringBootApplication
public class Application {
@Autowired
BookingService bookingService;
@Bean
BookingService bookingService() {
return new BookingService();
}
public static void main(String[] args) {
bookingService.book("Alice","Carol");
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
