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
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
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.