Master Spring Annotations: @Component vs @Bean, @Autowired vs @Resource, @ControllerAdvice
This article explains several often‑confused Spring annotations—including the differences between @Component and @Bean, the injection behaviors of @Autowired versus @Resource, the roles of @Component, @Repository, @Service, and @Controller, the purpose of @Configuration and @ControllerAdvice, and provides practical code examples for each.
Some Spring Annotations
1. Difference between @Component and @Bean
Target objects differ: @Component is applied to classes, while @Bean is applied to methods. @Component is usually detected automatically via classpath scanning (e.g., with @ComponentScan) and registered as a bean; @Bean defines a bean explicitly in a method, allowing custom creation. @Bean offers more flexibility and is required when registering third‑party classes that cannot be annotated with @Component.
@Bean usage example:
@Configuration
public class AppConfig {
@Bean
public TransferService transferService() {
return new TransferServiceImpl();
}
}@Component usage example:
@Component
public class ServiceImpl implements AService {
// ...
}Example that cannot be achieved with @Component:
@Bean
public OneService getService(status) {
case (status) {
when 1: return new serviceImpl1();
when 2: return new serviceImpl2();
when 3: return new serviceImpl3();
}
}2. Difference between @Autowired and @Resource
Both can inject beans into fields or setter methods. @Autowired performs injection by type by default and requires the dependency to exist unless required=false is set. @Resource injects by name by default; if no matching name is found, it falls back to type. The name can be specified with the name attribute.
Note: Once the name attribute is specified, injection is performed solely by name.
Combined usage of @Autowired with @Qualifier is equivalent to @Resource:
@Autowired(required = false) @Qualifier("example")
private Example example;
@Resource(name = "example")
private Example example;Injection order for @Resource:
If both name and type are specified, a unique matching bean must be found; otherwise an exception is thrown.
If only name is specified, a bean with that name is required.
If only type is specified, a unique bean of that type is required.
If neither is specified, Spring first attempts by name, then falls back to type.
3. Annotations that declare a class as a Spring bean
@Component: generic stereotype for any Spring-managed component. @Repository: marks a DAO layer class. @Service: marks a service‑layer class. @Controller: marks a Spring MVC controller. @Configuration: indicates a configuration class that can contain @Bean methods.
4. @Configuration: configuration class annotation
@Configurationsignals that the class may contain one or more @Bean methods, which the Spring container processes to create bean definitions at runtime.
@Configuration
public class AppConfig {
@Bean
public MyBean myBean() {
// instantiate, configure and return bean ...
}
}It can be registered programmatically:
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AppConfig.class);
ctx.refresh();
MyBean myBean = ctx.getBean(MyBean.class);
// use myBean ...It can also be loaded via component scanning together with @ComponentScan:
@Configuration
@ComponentScan("com.acme.app.services")
public class AppConfig {
// various @Bean definitions ...
}Constraints for @Configuration classes:
Must be a concrete class (cannot be a factory‑method return value).
Must not be final.
Must not be a local (inner) class unless declared static.
Nested configuration classes must be static.
@Bean methods should not create additional configuration classes.
5. @ControllerAdvice: global exception handling tool
Since Spring 3.2, @ControllerAdvice, @RestControllerAdvice and @RestController can be used to define @ExceptionHandler, @InitBinder, @ModelAttribute and apply them to all controller mappings such as @RequestMapping, @PostMapping, @GetMapping.
Typical usage combines @ControllerAdvice with @ExceptionHandler to handle custom exceptions globally:
@ControllerAdvice("com.developlee.errorhandle")
public class MyExceptionHandler {
@ResponseBody
@ExceptionHandler(CustomException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Map<String, Object> customExceptionHandler(CustomException e) {
Map<String, Object> map = new HashMap<>();
map.put("code", e.getCode());
map.put("msg", e.getMsg());
return map;
}
}Refer to the official Spring documentation for more details.
6. Differences among @Component, @Repository, @Service
@Componentis a generic singleton bean managed by Spring. @Repository, @Service, and @Controller are specialized stereotypes for persistence, service, and web layers respectively, providing additional semantics.
If a class is annotated with @Component, it can also be annotated with @Repository, @Service or @Controller, which may add layer‑specific behavior.
When unsure whether to use @Service or @Component for a business‑layer class, @Service is generally the better choice.
Summary
This brief overview covered several Spring annotations that are frequently used but often misunderstood, providing code snippets and practical guidance.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
