Defining a bean implicitly with @Component

Beans don't have to be defined in a Spring configuration class. Spring will automatically generate a bean from any class annotated with @Component.

Getting ready

We will use the basic web application created in the Creating a Spring web application recipe in Chapter 1, Creating a Spring Application.

Create the com.springcookbook.service package and the following service class in it:

public class UserService {
  public int findNumberOfUsers() {
    return 10;
  }
}

How to do it…

Here are the steps to define a bean by adding @Component to an existing class:

  1. In the Spring configuration file, in the @ComponentScan class annotation, add the com.springcookbook.service base package:
    @Configuration @EnableWebMvc @ComponentScan(basePackages ...

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.