I am trying to implement as of enterprise level, there they have folders like Repository,Service,ServiceImpl
In Services they have interface with method declaration
In ServiceImpl they have class implementing the interface of services
In Repository they have all Repository interfaces
BeanInjection is a class where we have all repositories and service classes and interfaces with @Autowired annotation.
When I tried to implement "@Autowired" to service class getting this Error.
Tried this no help link
Tried this no help but getting loop error link
Controller.java
public class SessionController extends BeanInjectionService {
@GetMapping
public ResponseEntity<List<Session>> list(){
LOGGER.info("Request received to view the sessions");
List<Session> sessions = sessionService.findAll();
LOGGER.info("Successfully fetched all the sessions");
return new ResponseEntity<>(sessions, HttpStatus.OK);
}
SessionService.java(Interface)
public interface SessionService {
List<Session> findAll();
}
SessionServiceImpl.java(Class)
public class SessionServiceImpl extends BeanInjectionService implements SessionService {
@Override
public List<Session> findAll(){
return sessionRepository.findAll();
}
BeanInjectionService.java(Class)
public class BeanInjectionService {
@Autowired
public SessionRepository sessionRepository;
**// Error Showing here while starting application
// Consider defining a bean of type 'com.example.conferencedemo.services.SessionService' in your configuration.**
@Autowired
public SessionService sessionService;
@Autowired
public SpeakerRepository speakerRepository;
@Autowired
public SpeakerService speakerService;
}
SessionRepository.java(Interface)
public interface SessionRepository extends JpaRepository<Session,Long> {
}
Thanks in advance
CodePudding user response:
I find using BeanInjectionService
a little weird, but I'll answer around it.
- Unless you add
@Service
onSessionServiceImpl
, you can't autowire it. - Circular dependency - If you do step 1, it will create a circular dependency because
SessionServiceImpl
needs its superclass object(BeanInjectionService
) to be created first. ButBeanInjectionService
cannot be created unless it finds an object ofSessionServiceImpl
. - To break the circular dependency, you have only one option. Don't extend
BeanInjectionService
. Rather, autowireSessionRepository
directly intoSessionServiceImpl
.
@Service
public class SessionServiceImpl implements SessionService {
@Autowired
private SessionRepository sessionRepository;
@Override
public List<Session> findAll(){
return sessionRepository.findAll();
}
}