In the context of Spring, A bean is a spring managed object. Here spring managed means an object created, initialised, managed, destroyed by Spring IoC container.
Whenever we mark a class with @Component
, Spring IOC container will create object for your class and manage it, Whenever we can simply get it from ApplicationContext
, or access it using @Autowired/@Resource/@Inject
annotations
We can also use @Controller, @Repository, @Service, @ControllerAdvice, @Configuration,@Aspect
in place of @Component
to tell more specifically that our class is a service or a repository or an aspect etc.
We can also use @Bean
annotation to create a bean from method return value
@Configuration
public class SolrConfig {
@Value("${spring.data.solr.host}") String solrUrl;
@Bean
public SolrServer solrServer() {
return new HttpSolrServer(solrUrl);
}
@Bean(name = "solrTemplate")
public SolrTemplate solrTemplate() {
return new SolrTemplate(new HttpSolrServer(solrUrl), RULE_ENGINE_CORE);
}
}