Bean Wiring: @Component, @Service, @Repository
Use stereotype annotations, define beans with @Bean, and understand component scanning.
Bean Wiring: @Component, @Service, @Repository is a free Java Academy lesson on CoddyKit. This is lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, and your progress syncs across the web and the CoddyKit app. The Java Academy course includes 4 lessons in total.
Stereotype Annotations
Spring provides stereotype annotations that mark classes as Spring-managed beans and convey their role: @Component (generic), @Service (business logic), @Repository (data access), @Controller/@RestController (web layer).
@Component: Generic Bean
Any class annotated with @Component is detected during component scan and registered as a Spring bean. It is the base for all other stereotypes.
@Component
public class EmailFormatter {
public String format(String to, String subject) {
return "To: " + to + "\nSubject: " + subject;
}
}@Service: Business Logic Layer
@Service is a specialization of @Component semantically indicating a service class. Spring treats it the same as @Component but it conveys intent and may be used by AOP advisors.
@Service
public class OrderService {
private final OrderRepository repo;
public OrderService(OrderRepository repo) { this.repo = repo; }
public Order placeOrder(Cart cart) { /* business logic */ return repo.save(new Order(cart)); }
}@Repository: Data Access Layer
@Repository marks DAO classes. Spring adds automatic persistence exception translation: SQLException and vendor-specific exceptions are wrapped in Spring's DataAccessException hierarchy.
@Repository
public class JdbcUserRepository {
private final JdbcTemplate jdbc;
public JdbcUserRepository(JdbcTemplate jdbc) { this.jdbc = jdbc; }
public User findById(long id) {
return jdbc.queryForObject("SELECT * FROM users WHERE id=?",
new BeanPropertyRowMapper<>(User.class), id);
}
}@Bean in @Configuration Classes
Use @Bean on a method inside a @Configuration class to manually register beans — useful for third-party classes you cannot annotate.
@Configuration
public class AppConfig {
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper().registerModule(new JavaTimeModule());
}
@Bean
public RestTemplate restTemplate() { return new RestTemplate(); }
}Component Scanning
@SpringBootApplication triggers component scanning from the application's package downward. Classes in sub-packages are discovered automatically. Use @ComponentScan(basePackages=...) to customize.
// Explicit scan (rarely needed in Spring Boot):
@SpringBootApplication
@ComponentScan(basePackages = {"com.example.app", "com.example.shared"})
public class MyApp { ... }Bean Naming
By default, the bean name is the uncapitalized class name (OrderService → orderService). Specify a custom name: @Service("orders") or @Bean("myMapper").
@Service("orderSvc")
public class OrderService { ... }
// Inject by name:
@Autowired @Qualifier("orderSvc")
private OrderService svc;Bean Scopes
Default scope is singleton (one instance per Spring context). Other scopes: prototype (new instance per injection), request, session (web only).
@Service
@Scope("prototype")
public class ReportBuilder {
private List<String> lines = new ArrayList<>();
public void addLine(String line) { lines.add(line); }
}@Primary and @Qualifier for Disambiguation
When multiple beans implement the same interface, use @Primary to mark the default, or @Qualifier("name") at the injection point to select a specific one.
@Service @Primary
public class CacheUserService implements UserService { ... }
@Service
public class DbUserService implements UserService { ... }
// Inject specific one:
@Autowired @Qualifier("dbUserService")
private UserService userService;Lazy Initialization
By default, singleton beans are created at startup. Annotate with @Lazy to defer creation until first use — useful for expensive beans rarely used.
@Service @Lazy
public class HeavyReportService {
public HeavyReportService() { System.out.println("Created on first use"); }
}@PostConstruct and @PreDestroy
Run initialization logic after dependency injection with @PostConstruct. Clean up resources before bean destruction with @PreDestroy.
@Service
public class CacheService {
@PostConstruct
public void init() { System.out.println("Cache warming up..."); }
@PreDestroy
public void cleanup() { System.out.println("Cache cleared."); }
}Quick Check
What additional behavior does @Repository add over @Component?
Recap
Use @Service for business logic, @Repository for DAO, @Component for utilities, @Bean for third-party types. @Primary/@Qualifier resolve multiple beans. @PostConstruct/@PreDestroy for lifecycle hooks.
Learn Java with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 104
- Lessons
- 374
Frequently Asked Questions
Is the “Bean Wiring: @Component, @Service, @Repository” lesson free?
Yes — the full text of “Bean Wiring: @Component, @Service, @Repository” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO. The Java Academy course includes 4 lessons in total.
What will I learn in “Bean Wiring: @Component, @Service, @Repository”?
Use stereotype annotations, define beans with @Bean, and understand component scanning. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.
How long does the “Bean Wiring: @Component, @Service, @Repository” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Auto-Configuration and Spring Boot Starters
- Application Properties and Profiles
- Bean Wiring: @Component, @Service, @Repository
- Constructor Injection and Circular Dependencies