2

I am new to spring boot , I have confusion that

@Autowired
serviceDemo serviceDemo

and getting bean from ApplicationContext is same or different? and if they are same then which method should I use

1 Answers1

0

It depends on what you’re trying to achieve, but to sum it up;

@Bean registers the instance in the application scope. That way it is accessible for later use.

@Autowired actually asks for an instance of a specific bean already registered in the scope.

Although it’s not exactly the same, you can consider for instance the @Service annotation. It tells spring that the class is a service and registers a bean of it in the scope. If you then have a different class, say a controller (@Controller or @RestController depending on your use case) and simply try to access the service you created you’ll most likely get an error thrown at you. This is because although your IDE might recognize the service location, spring doesn’t. Adding the @Autowired sets a “link” between the bean and the instantiation at the time of booting up your app.

  • Thanks for help but if I choose @autowired always then will it create any problem? – Prasad Walke Sep 18 '18 at 11:33
  • I don't believe it will cause any problems. However, as I mentioned, they do provide different functionalities. Depending on your environment I believe you can get fairly far without declaring a single bean, but it is much harder to avoid using the @Autowired declaration without running into walls. – Julian Torp Sep 18 '18 at 12:51
  • My bad, I completely overlooked the getBean part. They’re essentially the same, but @Autowired allows for late instantiation. – Julian Torp Sep 18 '18 at 13:31