Careeroza
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.
| Annotation | Use it on | Extra behaviour |
|---|---|---|
@Component | any general Spring-managed class | none, the base annotation |
@Service | business logic classes | none (documents intent) |
@Repository | data access classes | translates database exceptions into Spring's DataAccessException |
@Controller / @RestController | web layer classes | handles HTTP requests |
@Configuration | classes that define @Bean methods | see 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:runExample 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.