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:
In the Spring configuration file, in the
@ComponentScan
class annotation, add thecom.springcookbook.service
base package:@Configuration @EnableWebMvc @ComponentScan(basePackages = {"com.springcookbook.controller", "com.springcookbook.service"}) public class AppConfig { }
In the
UserService
class, add@Component
:@Component public class UserService { public int findNumberOfUsers() { return 10; ...