Issue
I am creating a spring boot project from scratch and trying to run my project but it failed to start. I am getting below error:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
***************************
APPLICATION FAILED TO START
***************************
Description:
Field users in com.example.demo.DataInitializer required a bean of type 'com.example.repository.UserDao' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.example.repository.UserDao' in your configuration.
This is my UserDao (Repository):
package com.example.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.model.User;
@Repository
public interface UserDao extends JpaRepository<User, Long>{
User findByEmail(String email);
User findByStatus(int status);
}
This is My DataInitializer file, that I am trying to run:
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import com.example.model.User;
import com.example.repository.UserDao;
@Component
public class DataInitializer implements CommandLineRunner{
@Autowired
UserDao users;
@Autowired
private PasswordEncoder passwordEncode;
@Override
public void run(String... args) throws Exception {
//System.out.println("Running spring boot demo application");
this.users.save(User.builder().email("[email protected]").phone("1234567890")
.username("Example Name").userid(10001L).build());
}
}
Solution
You either have to use @ComponentScan in your demo package (application class) or create packages from demo like:
example.demo.package1
example.demo.package2
instead of:
example.package1
(right click in demo package and create package from that one)
See https://www.baeldung.com/spring-component-scanning if you want to use component scanning and keep your package names.
If you have already put the packages and classes in one place, all you have to do is drag them to the correct package and refactor it since it will let you change names automatically.
Answered By - Jorge Hurtado