Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 385
Chandan Avatar asked Dec 25 '16 03:12

Chandan


1 Answers

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.

like image 62
Ken Bekov Avatar answered Oct 06 '22 00:10

Ken Bekov