Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 = {"com.springcookbook.controller", "com.springcookbook.service"})
    public class AppConfig {  
    }
  2. In the UserService class, add @Component:

    @Component
    public class UserService {
      public int findNumberOfUsers() {
        return 10;
    ...