This short post will help you understand the meaning and purpose of using the @Component annotation in Spring framework, with some code examples and explanation.

You know, @Component is a class-level annotation which you can use to indicate that an annotated class is a “component” - not surprisingly, literally as the name implies! A component is any class that encapsulates some logics or states of the application. That’s the semantic purpose of using @Component annotation.

And the technical purpose is that the annotated class will be a candidate for auto-detection when using annotation-based configuration and classpath scanning. That means Spring framework will create an instance of a @Component class and put that instance as a managed bean in the application context. Then this managed bean will be eligible for used by other components through dependency injection, such as via @Autowired field or constructor injection.

Another technical reason is that you can inject a Spring bean via autowired if the class is a component. Let’s see an example below:

import org.springframework.stereotype.Component;

@Component
public class ControllerHelper {
	
	// autowired possible because of @Component
	
	@Autowired private CustomerService customerService;	 
	
	public Customer getAuthenticatedCustomer(HttpServletRequest request) {
		// use CustomerService to get Customer object...
	}
}
In this example, the ControllerHelper class needs to use a managed bean of type CustomerService via dependency injection, but it’s not a service so using @Component annotation is appropriate in this case - the annotated class acts as a helper.

Then it can be used in another component, e.g. a controller as follows:

@Controller
public class ShoppingCartController {

	@Autowired private ControllerHelper controllerHelper;
	
	@GetMapping("/cart")
	public String viewCart(Model model, HttpServletRequest request) {
	
		Customer customer = controllerHelper.getAuthenticatedCustomer(request);
		
		// other processing...
		
		return "cart/shopping_cart";
	}
}
It’s also common to use @Component to implement a Java Servlet filter with Spring, as shown in the below example:

@Component
public class CommonFilter implements Filter {

	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		
		// processing...
		
		chain.doFilter(request, response);
	}

}
Here, because of the @Component annotation, Spring will consider the annotated class as filter and put the managed bean on its filter chain.

And another example where the @Component annotation is needed: implement authentication handler - as shown in the following code:

@Component
public class DatabaseLoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {


	@Override
	public void onAuthenticationSuccess(...)  {		
		
		// processing...
	}

}


Then it is used as below:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired private DatabaseLoginSuccessHandler databaseLoginHandler;
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
			.antMatchers("...").authenticated()
			.anyRequest().permitAll()
			.and()
			.formLogin()
				...
				.successHandler(databaseLoginHandler)
				.permitAll()
			...
	}
}
You can specify name of the managed bean explicitly, as shown in the below example:

package net.codejava;

import org.springframework.stereotype.Component;

@Component("helper")
public class CommonHelper {
	
	public String getName() {
		return "CodeJava.net";
	}
}
Here, the managed bean will be assigned the name “helper”. Then you must specify this name in the code that gets the bean from Spring application context, as follows:

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.scan("net.codejava");
context.refresh();

CommonHelper helper = (CommonHelper) context.getBean("helper");
System.out.println(helper.getName());
So that you have learnt the meaning, purpose and usage of the @Component annotation in Spring framework with various code examples. I hope you found this post helpful. You can also watch the following video to see the coding in action:

 

Reference:

Annotation Interface Component (Spring Docs)

 

Other Spring Annotations:

 


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment