I m trying to follow a Spring Boot example , I searched on internet for few hours without find a solution to my case . most of solution I found they said to put @ComponentScan to scan the package , am I missing something , any hep is appreciated .
SpringBootApplication class:
package ben;
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan({"services","repository", "web"})
public class SpringBootWebApplication
{
public static void main (String [] args) {
SpringApplication.run(SpringBootWebApplication.class, args);
}
}
PersonRepository class:
package ben.repository;
@Repository
public interface PersonRepository extends CrudRepository<Bde, Integer> {
}
PersonService:
package ben.services;
import models.Bde;
public interface PersonService
{
public Iterable <Bde> findAll();
}
PersonServiceImpl:
package ben.services;
@Service
public class PersonServiceImpl implements PersonService
{
@Autowired
private PersonRepository personRepository;
@Override
public Iterable<Bde> findAll()
{
return personRepository.findAll();
}
}
PersonRest class:
package ben.web;
@RestController
public class PersonRest
{
@Autowired
//@Qualifier("PersonServiceImpl")
private PersonService personService;
@RequestMapping("/person")
@ResponseBody
public Iterable <Bde> findAll() {
Iterable <Bde> persons=personService.findAll();
return persons;
}
}
package structure updated like suggested :
You are limiting yourself to the package service
@ComponentScan("services")
this is equal to
@ComponentScan(basePackages = "services")
You need to specify all packages in order for your beans to be instantiated
An example on how to scan all your beans (services, repository and web)
@ComponentScan({"services","repository", "web"})
As an alternative you can do the following:
- move everything in a package and the
SpringBootWebApplication
class would sit at the root of that package.
An example:
All your app sits on com.yourapp
. If you put the SpringBootWebApplication
in com.yourapp
, there is not need for the @ComponentScan
annotation anymore and your class gets simplified just with the @SpringBootApplication
:
package com.yourapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootWebApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootWebApplication.class, args);
}
}