Search code examples
springspring-bootspring-annotations

what is the difference between @Bean annotation and @Component annotation at Spring?


It might be a very simple question for you.But I read lots of documents and I am totally confused.We can use @Component instead of @Bean or @Bean instead of @Component(as well as @Repository @Service @Controller) ?

Cheers


Solution

  • Component

    @Component also for @Service and @Repository are used to auto-detect and auto-configure beans using classpath scanning.

    As long as these classes are in under our base package or Spring is aware of another package to scan, a new bean will be created for each of these classes

    Bean and Component are mapped as one to one i.e one bean per Class.

    These annotations (@Component, @Service, @Repository) are Class level annotations.

    Example:

    Lets Say we have a UserService Class which contains all methods for User Operation.

    @Service
    public class UserService {
    
        @Autowired
        private UserRepository userRepository;
    
        @Override
        public User findByUsername( String username ) throws UsernameNotFoundException {
            User u = userRepository.findByUsername( username );
            return u;
        }
    
        public List<User> findAll() throws AccessDeniedException {
            List<User> result = userRepository.findAll();
            return result;
        }
    }
    

    Spring will create a Bean for UserService and we can use this at multiple location/classes.

    @Bean

    @Bean is used to declare a single bean, rather than letting Spring do it automatically as in case of Component.

    It decouples the declaration of the bean from the class definition, and lets you create and configure beans exactly how you choose.

    @Bean are used at method level and can be configured as required

    eg:

    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        
        @Bean
        public SpringTemplateEngine springTemplateEngine()
        {
            SpringTemplateEngine templateEngine = new SpringTemplateEngine();
            templateEngine.addTemplateResolver(htmlTemplateResolver());
            return templateEngine;
        }
    
           @Bean
        public SpringResourceTemplateResolver htmlTemplateResolver()
        {
            SpringResourceTemplateResolver emailTemplateResolver = new SpringResourceTemplateResolver();
            emailTemplateResolver.setPrefix("classpath:/static/template/");
            emailTemplateResolver.setSuffix(".html");
            emailTemplateResolver.setTemplateMode("HTML");
            emailTemplateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
            return emailTemplateResolver;
        }
    
    
    ...
    

    Read more about Stereotype Annotations here.