The simplest way to define a bean is to create, in a Spring configuration class, a method annotated with @Bean returning an object (the actual bean). Such beans are usually used to configure Spring in some way (database, security, view resolver, and so on). In this recipe, we'll define a bean that contains the connection details of a database.
How to do it…
In a Spring configuration class, add a dataSource() method annotated with @Bean and return a Datasource object. In this method, create a DriverManagerDataSource object initialized with the connection details of a database:
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
Using a bean via dependency injection with @Autowired
Spring configuration beans, such as the one in the Defining a bean explicitly with @Bean recipe are automatically discovered and used by Spring. To use a bean (any kind of bean) in one of your classes, add the bean as a field and annotate it with @Autowired. Spring will automatically initialize the field with the bean. In this recipe, we'll use an existing bean in 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 use an existing bean in one of your classes:
In the controller class, add a UserService field annotated with @Autowired:
@Autowired
UserService userService;
In a controller method, use the UserService field:
@RequestMapping("hi")
@ResponseBody
public String hi() {
return "nb of users: " + userService.findNumberOfUsers();
}
In a web browser, go to http://localhost:8080/hi to check whether it's working.
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 its getBean() method to retrieve the UserService bean:
In this recipe, you will learn how to define a controller method to be executed for a given route.
How to do it…
Here are the steps for creating a controller method for a given route:
Create a controller class in your controller package (for example, com.springcookbook.controller). This is a normal Java class annotated with @Controller:
@Controller
public class UserController {
...
}
Add a controller method. This is a standard Java method annotated with @RequestMapping, which takes the route as a parameter: