what is the difference between @Bean annotation and @Component annotation at Spring?
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.
Are @Bean and @Component annotations the same but for different targets in Spring Framework?
Not quite. They belong to different concepts.
@Component
is a stereotype annotation. A class annotated with this annotation will be auto detected during class path scanning. See also Spring reference documentation chapter 5.10. Other than that the @Bean
annotation belongs to the Java configuration feature. Within a configuration class this annotation is used to mark methods that define beans.
Why is Spring's @Component Annotation RUNTIME?
The component scanning is done at the startup, not at the compilation.
Also, the aspects (AOP) are created at the runtime
What is the difference between @Configuration and @Component in Spring?
@Configuration Indicates that a class declares one or more @Bean
methods and may be processed by the Spring container to generate bean
definitions and service requests for those beans at runtime@Component Indicates that an annotated class is a "component". Such
classes are considered as candidates for auto-detection when using
annotation-based configuration and classpath scanning.@Configuration is meta-annotated with @Component, therefore
@Configuration classes are candidates for component scanning
You can see more here:
http://docs.spring.io/spring-framework/docs/4.0.4.RELEASE/javadoc-api/org/springframework/context/annotation/Configuration.html
A @Configuration is also a @Component, but a @Component cannot act like a @Configuration.
Related Topics
Java.Sql.Sqlexception: - Ora-01000: Maximum Open Cursors Exceeded
Closing Database Connections in Java
Differencebetween & and && in Java
Why Does Ssl Handshake Give 'Could Not Generate Dh Keypair' Exception
Why Are Local Variables Not Initialized in Java
Java.Lang.Unsupportedclassversionerror: Bad Version Number in .Class File
String's Maximum Length in Java - Calling Length() Method
Random Weighted Selection in Java
How to Subtract X Days from a Date Using Java Calendar
Add Image Thumbnails to a Layout in a Grid
Look and Feel Is Not Updating in Swing Jtabbedpane
No Compiler Is Provided in This Environment. Perhaps You Are Running on a Jre Rather Than a Jdk
What Exactly Is Field Injection and How to Avoid It
Why Is Spring's Applicationcontext.Getbean Considered Bad
What Is Variable Shadowing Used for in a Java Class
How to Set a Background Picture in JPAnel
Replace Implicit Wait with Explicit Wait (Selenium Webdriver & Java)