Using a bean directly
It's possible to get a bean directly from Spring instead of using dependency injection by making Spring's ApplicationContext
, which contains all the beans, a dependency of your class. In this recipe, we'll inject an existing bean into a controller class.
Getting ready
We will use the code from the Defining a bean implicitly with @Component recipe, where we defined a UserService
bean.
How to do it…
Here are the steps to get and use a bean directly:
- In the controller class, add an
ApplicationContext
field annotated with@Autowired
:@Autowired private ApplicationContext applicationContext;
- In a controller method, use the
ApplicationContext
object and itsgetBean()
method to retrieve theUserService
bean:UserService userService = (UserService)applicationContext.getBean("userService");
How it works…
When the controller class is instantiated, Spring automatically initializes the @Autowired
field with its ApplicationContext
object. The...