Dunguyen
Dunguyen

Reputation: 81

Spring Boot @Autowired does not work with class of different package

The structure of my project like the following:

enter image description here

I am sure everything okay but only one thing make the problem is @Autowired in StoredProcedureSpringDataJpaApplication.java like the following:

public class StoredProcedureSpringDataJpaApplication implements CommandLineRunner {
    @Autowired
    private StudentRepository stu;
    
    public static void main(String[] args)  {
         SpringApplication.run(StoredProcedureSpringDataJpaApplication.class, args); 
        
    }

    @Override
    public void run(String... args) throws Exception {
        // TODO Auto-generated method stub
        
        List<Student> students = stu.findAll();
        students.forEach(System.out :: println);
        
    }

}

Error description is:

Field stu in com.example.demo.StoredProcedureSpringDataJpaApplication required a bean of type 'com.repository.StudentRepository' that could not be found.

I know this is familiar question ,I did so many way to try to solve this problem in the internet even in stackoverflow but all can not solve my problem.

Help me solve this problem.

Upvotes: 0

Views: 1260

Answers (3)

Benjamin M
Benjamin M

Reputation: 24527

This happens because @SpringBootApplication does only scan in the package where it is defined.

Make sure it is placed at the root of your project and everything that should be scanned below it. For example:

com
  - example
      - demo
          - StoredProcedureSpringDataJpaApplication.java
          - repository
              - StudentRepository.java

Upvotes: 0

Niraj Jha
Niraj Jha

Reputation: 585

Your package structure is incorrect StoredProcedureSpringDataJpaApplication.java should be in the root package. Another way is component scan placing annotation over StoredProcedureSpringDataJpaApplication.java. In your case, it should be like

package structure

This won't work for the repository class and as you have a different package structure so @EnableJpaRepositories(basePackages = "com.repository") will help you resolve this issue.

Upvotes: 1

Panagiotis Bougioukos
Panagiotis Bougioukos

Reputation: 18909

Use @ComponentScan({"com.example.demo", "com.repository"})

By default without this annotation it considers only annotations that exist inside the package where your @SpringBootApplication is declared, aka com.example.demo

Also together with the @ComponentScan use the following

@EnableJpaRepositories(basePackages = {"com.repository"})

Upvotes: 1

Related Questions