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"); ...

Get Spring Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.