Defining a bean explicitly with @Bean
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();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/db1");
dataSource.setUsername("root");
dataSource.setPassword("123");
...