J.E.Y J.E.Y - 1 month ago 13
Java Question

@Service annotated bean wasn't picked up by SpringBootApplication

I used SpringBootApplication in a small project. The architecture is simple:

Entry file:

@SpringBootApplication
@PropertySource("classpath:application.properties")
public class RptApp implements CommandLineRunner
{
@Autowired private RptService rptService;
@Override
public void run(String... args) throws Exception {
rptService.doStuff(){...};
}
}


In which RptService is an interface and it has an implementation: RptServiceImpl.java. It's that the RptServiceImpl.java was annotated with @Service.

@Service
public class RptServiceImpl implements RptService {
@Override
public void doStuff();
}


My understanding is that @SpringBootApplication already embeds @ComponentScan, @EnableComponentScan (or something like that), @Configuration so that rptService should be automatically wired by the container. Rather it threw an error like:

Description:

Field RptService in XXXX.RptApp required a bean of type 'xxx.xxx.xxx.RptService' that could not be found.


Action:

Consider defining a bean of type 'xxx.xxx.xxx.RptService' in your configuration.


I know how to find the workaround basing on the hint, that besides the point though.

I did write another simple class Client and annotate it with @Component and @Autowired it in the main file. Spring didn't have problem picking that up.

The relevant part of my pom file looks like:

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.4.1.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
....


anyone might shed a light?

Answer

RptService should be in the main entry file's sub directory to be picked Spring @ComponentScan

Comments