Beans and Stereotype Annotations

Telling Spring Which Classes to Manage

Put a stereotype annotation on a class and Spring's component scan finds it (in the main class's package and sub-packages) and creates one bean of it.

AnnotationUse it onExtra behaviour
@Componentany general Spring-managed classnone, the base annotation
@Servicebusiness logic classesnone (documents intent)
@Repositorydata access classestranslates database exceptions into Spring's DataAccessException
@Controller / @RestControllerweb layer classeshandles HTTP requests
@Configurationclasses that define @Bean methodssee next topic

ShopEase Beans

package com.shopease.product;

import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import java.util.List;

@Repository
public class ProductRepository {
    public List<String> findAllNames() {
        return List.of("Boat Rockerz 450", "Clean Code");
    }
}

@Service
public class ProductService {
    private final ProductRepository repository;

    public ProductService(ProductRepository repository) {   // Spring injects the bean
        this.repository = repository;
    }

    public int countProducts() {
        return repository.findAllNames().size();
    }
}

Note: In a real project each public class goes in its own file. They are shown together here to save space.

Getting a Bean from the Context

You rarely do this in application code (injection is preferred), but it shows what the container holds:

@SpringBootApplication
public class ShopeaseApplication {
    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(ShopeaseApplication.class, args);
        ProductService service = ctx.getBean(ProductService.class);
        System.out.println("Products: " + service.countProducts());
        System.out.println("productService bean exists: " + ctx.containsBean("productService"));
    }
}

Example

./mvnw spring-boot:run

Example output

... Started ShopeaseApplication in 1.912 seconds (process running for 2.2)
Products: 2
productService bean exists: true

Tip: Default bean name = class name with a lowercase first letter: ProductService becomes productService.