Home > Net >  How can I use a JpaRepository, with @Autowired, inside a service class?
How can I use a JpaRepository, with @Autowired, inside a service class?

Time:07-09

I've already read these questions and none of them worked:

Spring boot MVC - Unable to Autowire Repository in the service class

Why can't @Autowired a JPA repository - Spring boot JPA

JpaRepository getting Null at service class

And also this one: https://www.baeldung.com/spring-autowired-field-null

Unfortunately, none of them worked.

What I have is:

Service interface:

@Service
public interface DayTradeService {
    public List<DayTrade> getDayTrades(List<NotaDeCorretagem> corretagens);
}

Service Implementation:

public class DayTradeServiceImpl implements DayTradeService {
    
    @Autowired
    private DayTradeRepository dayTradeRepository;
    
    @Override
    public List<DayTrade> getDayTrades(List<NotaDeCorretagem> corretagens) {
        // Several lines of code and some of them is trying to use dayTradeRepository.
    }
}

My DayTradeRepository:

@Repository
public interface DayTradeRepository extends JpaRepository<DayTrade, Integer> {}

Inside my DayTradeController (annotated with @Controller), I can use a dayTradeRepository with @Autowired. But inside a service class, I cannot use. I get this message:

Cannot invoke "meca.irpf.Repositories.DayTradeRepository.getDayTrades()" because "this.dayTradeRepository" is null"

How can I make it possible?

EDIT after I accepted Nikita's answer:

I didn't post the Controller code, but it didn't have the @Autowired for the service class DayTradeServiceImpl. That was the point I was missing. After Nikita pointing that, I could solve the problem.

CodePudding user response:

You not need create new object. You have to call like this:

@Controller
@RequestMapping("/test")
public class TestController {

    @Autowired
    private DayTradeServiceImpl dayTradeService;


    @GetMapping(value = "/get")
    public void getTrades() {
        dayTradeService.getDayTrades(...);
    }

}

And set annotation @Service for DayTradeServiceImpl.

@Service
public class DayTradeServiceImpl implements DayTradeService {
    
    @Autowired
    private DayTradeRepository dayTradeRepository;
    
    @Override
    public List<DayTrade> getDayTrades(List<NotaDeCorretagem> corretagens) {
        // Several lines of code and some of them is trying to use dayTradeRepository.
    }
}

Spring framework use inversion of control, which has container for beans. For detect beans use annotation like: @Service, @Component, @Repository.

  • Related