Chandan
Chandan

Reputation: 133

How does a Spring Boot Application create beans without @Configuration class

I am pretty new to Spring Boot Application. I wanted to understand how does a spring Boot Application create beans without @Configuration class . I had a look at a sample project where there was neither @Bean definitions nor a component scan yet @Autowired provided the dependency to the class. Please have a look at the snippet below:

@RestController
public class RestController{

**@Autowired
public CertificationService certificationService;**
.
.
.
.
}

//Interface

public interface CertificationService{

public List<Certification> findAll();

}

//Implementation Class
@Transactional
@Service

public class CertificationServiceImpl{

public List<Certification> findAll(){
.
.
}

}

My limited knowledge of springs tells me that when there is a @Service annotation over a class, there has to be a @ComponentScan somewhere to create the bean. But without a component scan, how does the CertificationServiceImpl bean gets created and thereby how does the autowiring of CertificationService in RestController works here?

Upvotes: 10

Views: 1638

Answers (1)

Ken Bekov
Ken Bekov

Reputation: 14015

As said in documentation:

... The @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration and @ComponentScan...

Let say you have Spring Boot app class something like:

package com.mypackage;

import org.springframework.boot.SpringApplication;    
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication    
public class SpringBootApplication {    
    public static void main(String[] args) {    
        SpringApplication.run(SpringBootApplication.class, args);    
    }    
}

Then all packages below of package com.mypackage will be scanned by default for Spring components. By the way, you can specify packages to scan right in @SpringBootApplication annotation, without usage of @ComponentScan. More details here.

Upvotes: 8

Related Questions