Spring Autowired服务为null

时间:2017-04-21 08:27:37

标签: java spring spring-boot spring-data spring-data-jpa

我有RestController类,它调用Presenter来获取一些数据。

@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类里面我想做Spring服务的@Autowire,但是我得到空指针异常。服务总是为空。

@Component
public class DatabaseDataSource implements NotesDataSource {

@Autowired
private NotesService notesService;

public DatabaseDataSource(){
}

@Override
public List<Note> getAll() {
    return notesService.getAll();
}

}

1 个答案:

答案 0 :(得分:1)

即使您已将DatabaseDataSource注释为@Component,您也不会注入,因此在此过程中将其用作Spring Bean。你只需手动创建它:

public GetAllNotesPresenterImpl(){

    dataSource = new DatabaseDataSource();
    repository = new NotesRepositoryImpl(dataSource);
}

为了利用这种豆的注射:

@Autowired
private NotesService notesService;

你需要从顶部开始使用Spring注入(这只是你可以采用的方法之一):

1)在控制器中注入dataSource:

@RestController
@RequestMapping(value="notes/api")
public class NotesRestController {

private GetAllNotesPresenter getAllNotesPresenter;

@Autowired
private NotesDataSource dataSource;

@RequestMapping(value="/all")
public List<Note> getAll(){
    getAllNotesPresenter = new GetAllNotesPresenterImpl(dataSource);
    return getAllNotesPresenter.getAll();
}

2)更改GetAllNotesPresenterImpl的构造函数:

public GetAllNotesPresenterImpl(NotesDataSource dataSource){

    this.dataSource = dataSource;
    repository = new NotesRepositoryImpl(dataSource);
}

其他选项是将GetAllNotesPresenterImplNotesRepositoryImpl作为spring bean并直接在NotesRepositoryImpl中注入dataSource。最后的电话由你决定。