TLDR: я играю с простым приложением Spring Boot, которое, похоже, не работает и выдает два вида ошибок в зависимости от того, как я его запускаю:
1) Утверждая, что 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.
2) Поэтому я переместил все подпакеты в основной пакет, содержащий класс приложения: ![enter image description here](https://i.stack.imgur.com/Y42ds.png)
так что теперь ВТОРАЯ ошибка, которая заменила ее, была страница localhost:8080
ничего не загружает (ошибка 404).
Основная часть ниже >>>
Общая структура пакета выглядит следующим образом:
![enter image description here](https://i.stack.imgur.com/MwQWA.png)
Мой код для услуги:
@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);
}
}
Не могу понять, где я ошибся, убедившись, что все зависимости были должным образом автоматически подключены и использованы соответствующим образом, плюс все они находятся в одном основном пакете. Я что-то здесь упускаю? Я думаю, поскольку сервис, модель и слои репо находятся в одном основном пакете, мне даже не нужно добавлять @ComponentScan
верно? Спасибо!
Продолжение:
Отмеченный компонент, NotesRepository был добавлен через его пакет @ComponentScan{...}
, но, похоже, он тоже не работает.
РЕДАКТИРОВАТЬ 2:
Я попытался переместить все пакеты в основной пакет приложения следующим образом:
![enter image description here](https://i.stack.imgur.com/Y42ds.png)
Теперь приложение весенней загрузки работает успешно, но когда я запускаю localhost: 8080 на chrome, я получаю страницу ошибки Whitelabel:
![enter image description here](https://i.stack.imgur.com/iVUAS.png)