【发布时间】:2020-08-13 15:49:43
【问题描述】:
TLDR:我正在玩一个简单的 Spring Boot 应用程序,该应用程序似乎无法正常工作,并根据我的运行方式引发两种错误:
1) 声称找不到repo bean:
Field notesRepository in com.demo.service.CreateNoteService required a bean of type 'com.demo.models.NotesRepository' 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 'learnk8s.io.demo.models.NotesRepository' in your configuration.
所以现在替换它的第二个错误是 localhost:8080 页面不加载任何内容(404 错误)。
下面的主体>>>
整体包结构是这样的:
我的服务代码:
@Slf4j
@Transactional
@Service
public class CreateNoteService implements NoteService {
@Autowired
NotesRepository notesRepository;
@Override
public void saveNote(String description, Model model) {
// Check input
if(description != null && !description.trim().isEmpty()) {
notesRepository.save(new Note(null, description.trim()));
log.info("Saved note successfully");
//After publish you need to clean up the textarea
model.addAttribute("description", "");
}
}
@Override
public void getAllNotes(Model model) {
List<Note> notes = notesRepository.findAll();
Collections.reverse(notes);
model.addAttribute("notes", notes);
}
}
以及存储库的代码(使用 mongoDb):
@Repository
public interface NotesRepository extends MongoRepository<Note, String> {
}
我的控制器类的代码:
@Slf4j
@Controller
public class NoteController {
@Autowired
CreateNoteService createNoteService;
@GetMapping("/")
public String index(Model model) {
createNoteService.getAllNotes(model);
return "index";
}
@PostMapping("/note")
public String saveNotes(@RequestParam("image") MultipartFile file,
@RequestParam String description, @RequestParam(required = false) String publish, @RequestParam(required = false) String upload, Model model) throws IOException {
if (publish != null && publish.equals("Publish")) {
createNoteService.saveNote(description, model);
createNoteService.getAllNotes(model);
return "redirect:/";
}
// After save fetch all notes again
return "index";
}
}
最后,主要应用程序:
@SpringBootApplication
@ComponentScan(basePackages = {"com.demo.controller", "com.demo.models", "com.demo.service"})
public class MainJavaApplication {
public static void main(String[] args) {
SpringApplication.run(MainJavaApplication.class, args);
}
}
我看不出我在确保所有依赖项都被适当地自动装配并相应地使用方面出了什么问题,而且所有依赖项都在同一个主包下。我在这里错过了什么吗?我在想,因为服务、模型和 repo 层都在同一个主包中,我什至不需要添加 @ComponentScan 对吗?谢谢!
继续:
@ComponentScan{...} 通过它的包添加了标记出来的 bean,NotesRepository,但这似乎也不起作用。
编辑 2:
我尝试将所有包转移到主应用程序包中,如下所示:
现在 spring boot 应用程序运行成功,但是当我在 chrome 上运行 localhost:8080 时,我得到一个 Whitelabel 错误页面:
【问题讨论】:
-
现在工作了吗?
-
不,不是。请参阅 EDIT 2 以查看新错误谢谢!
-
当您尝试通过浏览器获取 GET 时,应用程序会记录什么?
-
您现在遇到了一个新问题,与您原来的问题无关。请为此打开一个单独的问题
-
另外,@MichaelKreutz 的建议似乎对您有所帮助。我会考虑支持他的回答,并选择他的回答作为你问题的答案。
标签: java spring spring-boot