0

lets say I have code like this:

@Repository
public class Foo{
}

@Service
public class Boo{

@Autowired
private Foo foo;
}

so now what here are we calling bean? Bean is the object of Foo type of refrence "foo" BUT are Boo class annotated as Service and Foo as Repository ALSO beans? Ihve been using spring for a while now but this basic question makes me feel bad for not knowing...

filemonczyk
  • 1,613
  • 5
  • 26
  • 47
  • 1
    Possible duplicate of [What in the world are Spring beans?](http://stackoverflow.com/questions/17193365/what-in-the-world-are-spring-beans) – eltabo Oct 19 '16 at 08:59

3 Answers3

3

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);
    }
}
Naresh Joshi
  • 4,188
  • 35
  • 45
0

All of your application components (@Component, @Service, @Repository, @Controller etc.) will be automatically registered as Spring Beans

http://docs.spring.io/autorepo/docs/spring-boot/current/reference/html/using-boot-spring-beans-and-dependency-injection.html

Witold Kaczurba
  • 9,845
  • 3
  • 58
  • 67
0

Defining Beans can be thought of as replacing the keyword new.

Further information can be found here which might be helpful for understanding Beans in Spring.

Muhammad Waqas Dilawar
  • 1,844
  • 1
  • 23
  • 34