【发布时间】:2017-04-21 08:27:37
【问题描述】:
我有调用 Presenter 来获取一些数据的 RestController 类。
@RestController
@RequestMapping(value="notes/api")
public class NotesRestController {
private GetAllNotesPresenter getAllNotesPresenter;
@RequestMapping(value="/all")
public List<Note> getAll(){
getAllNotesPresenter = new GetAllNotesPresenterImpl();
return getAllNotesPresenter.getAll();
}
}
在 Presenter 类中我调用 DataSource(不是 Spring Repository,只是 DAO 类)。
public class GetAllNotesPresenterImpl implements GetAllNotesPresenter {
private NotesDataSource dataSource;
private NotesRepository repository;
public GetAllNotesPresenterImpl(){
dataSource = new DatabaseDataSource();
repository = new NotesRepositoryImpl(dataSource);
}
@Override
public List<Note> getAll() {
return repository.getAll();
}
}
这是我的 Repository 类,它不是 Spring Repository,它只是 DAO 类。
public class NotesRepositoryImpl implements NotesRepository {
private NotesDataSource dataSource;
public NotesRepositoryImpl(NotesDataSource dataSource){
this.dataSource = dataSource;
}
@Override
public List<Note> getAll() {
return dataSource.getAll();
}
}
这是我的服务类:
@Service
@Transactional
public class NotesServiceImpl implements NotesService {
@Autowired
private NotesJpaRepository repository;
@Override
public List<NoteJpa> getAll() {
return repository.findAll();
}
}
在DataSource类里面我想做@Autowire的Spring服务,但是我得到空指针异常。服务总是空的。
@Component
public class DatabaseDataSource implements NotesDataSource {
@Autowired
private NotesService notesService;
public DatabaseDataSource(){
}
@Override
public List<Note> getAll() {
return notesService.getAll();
}
}
【问题讨论】:
-
如果上面的代码是正确的,我猜
NotesService将永远不会被构造(并且之前抛出异常),因为它期望NotesJpaRepository你要么没有提到要么不是一个bean .如果这应该是NotesRepository的实现,它必须被实例化并作为 bean 公开。 -
NotesService接口有@Service注解吗?
标签: java spring spring-boot spring-data spring-data-jpa