У меня есть приложение Spring Boot с приведенной ниже структурой.
banking-app
├── backend
│ ├── src
│ │ ├── main
│ │ │ ├── java
│ │ │ │ └── com
│ │ │ │ └── bank
│ │ │ │ ├── controller
│ │ │ │ ├── model
│ │ │ │ ├── repository
│ │ │ │ ├── service
│ │ │ │ └── BankingAppApplication.java
│ │ │ ├── resources
│ │ │ │ ├── application.properties
│ │ │ │ └── static
│ │ │ │ ├── css
│ │ │ │ ├── js
│ │ │ │ └── images
│ │ │ └── templates
│ │ │ └── index.html (or Thymeleaf template)
├── pom.xml
└── README.md
В пакетах контроллера и службы имеются CustomerController.java и CustomerService.java соответственно. Коды для обоих добавлены ниже.
CustomerController.java
package com.bank.bankingapp.controller;
import com.bank.bankingapp.model.Customer;
import com.bank.bankingapp.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@Controller
@RequestMapping("/customers")
public class CustomerController {
private final CustomerService customerService;
@Autowired
public CustomerController(CustomerService customerService) {
this.customerService = customerService;
}
@GetMapping
public String getAllCustomers(Model model) {
List customers = customerService.getAllCustomers();
model.addAttribute("customers", customers);
return "customer/customer-list"; // Returns the Thymeleaf template for the customer list
}
@GetMapping("/create")
public String showCreateForm(Model model) {
model.addAttribute("customer", new Customer()); // Empty form object to bind to
return "customer/customer-create"; // Thymeleaf template to render the form
}
@PostMapping
public String createCustomer(@ModelAttribute Customer customer) {
customerService.createCustomer(customer); // Create the new customer
return "redirect:/customers"; // Redirect to the list of customers after creation
}
@GetMapping("/{id}")
public String showCustomerDetail(@PathVariable String id, Model model) {
Optional customer = customerService.getCustomerById(id);
if (customer.isPresent()) {
model.addAttribute("customer", customer.get());
return "customer/customer-detail"; // Thymeleaf template for displaying customer details
}
return "redirect:/customers"; // Redirect if the customer is not found
}
@GetMapping("/{id}/edit")
public String showEditForm(@PathVariable String id, Model model) {
Optional customer = customerService.getCustomerById(id);
if (customer.isPresent()) {
model.addAttribute("customer", customer.get());
return "customer/customer-edit"; // Thymeleaf template for editing the customer
}
return "redirect:/customers"; // Redirect if the customer is not found
}
@PostMapping("/{id}/edit")
public String updateCustomer(@PathVariable String id, @ModelAttribute Customer customer) {
customerService.updateCustomer(id, customer); // Update the customer
return "redirect:/customers"; // Redirect to the list of customers after updating
}
@GetMapping("/{id}/delete")
public String deleteCustomer(@PathVariable String id) {
customerService.deleteCustomer(id); // Delete the customer
return "redirect:/customers"; // Redirect to the list of customers after deletion
}
}
CustomerService.java
package com.bank.bankingapp.service;
import com.bank.bankingapp.model.Customer;
import com.bank.bankingapp.repository.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class CustomerService {
private final CustomerRepository customerRepository;
@Autowired
public CustomerService(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}
public List getAllCustomers() {
return customerRepository.findAll();
}
public Optional getCustomerById(String id) {
return customerRepository.findById(id);
}
public Customer createCustomer(Customer customer) {
return customerRepository.save(customer);
}
public Customer updateCustomer(String id, Customer customer) {
customer.setId(id);
return customerRepository.save(customer);
}
public void deleteCustomer(String id) {
customerRepository.deleteById(id);
}
}
Класс приложения приведен ниже.
package com.bank.bankingapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages = {"com.bank.bankingapp","com.bank.bankingapp.service","com.bank.bankingapp.controller","com.bank.bankingapp.model","com.bank.bankingapp.repository"})
public class BankingApplication {
public static void main(String[] args) {
SpringApplication.run(BankingApplication.class, args);
}
}
Приложение не запускается из-за проблемы с зависимостью компонента.
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customerController' defined in file [C:\Users\Debaditya Bhuyan\OneDrive\Downloads\Consultancy\Open Source Development\ja
va\banking-application\target\classes\com\bank\bankingapp\controller\CustomerController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.bank.bankingapp.service.CustomerService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.bank.bankingapp.service.CustomerService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Подробнее здесь: https://stackoverflow.com/questions/793 ... -factory-u
Не удалось загрузить ApplicationContext. Причина: org.springframework.beans.factory.UnsatisfiedDependencyException: ошиб ⇐ JAVA
Программисты JAVA общаются здесь
1736250762
Anonymous
У меня есть приложение Spring Boot с приведенной ниже структурой.
banking-app
├── backend
│ ├── src
│ │ ├── main
│ │ │ ├── java
│ │ │ │ └── com
│ │ │ │ └── bank
│ │ │ │ ├── controller
│ │ │ │ ├── model
│ │ │ │ ├── repository
│ │ │ │ ├── service
│ │ │ │ └── BankingAppApplication.java
│ │ │ ├── resources
│ │ │ │ ├── application.properties
│ │ │ │ └── static
│ │ │ │ ├── css
│ │ │ │ ├── js
│ │ │ │ └── images
│ │ │ └── templates
│ │ │ └── index.html (or Thymeleaf template)
├── pom.xml
└── README.md
В пакетах контроллера и службы имеются [b]CustomerController.java[/b] и [b]CustomerService.java[/b] соответственно. Коды для обоих добавлены ниже.
[b]CustomerController.java[/b]
package com.bank.bankingapp.controller;
import com.bank.bankingapp.model.Customer;
import com.bank.bankingapp.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@Controller
@RequestMapping("/customers")
public class CustomerController {
private final CustomerService customerService;
@Autowired
public CustomerController(CustomerService customerService) {
this.customerService = customerService;
}
@GetMapping
public String getAllCustomers(Model model) {
List customers = customerService.getAllCustomers();
model.addAttribute("customers", customers);
return "customer/customer-list"; // Returns the Thymeleaf template for the customer list
}
@GetMapping("/create")
public String showCreateForm(Model model) {
model.addAttribute("customer", new Customer()); // Empty form object to bind to
return "customer/customer-create"; // Thymeleaf template to render the form
}
@PostMapping
public String createCustomer(@ModelAttribute Customer customer) {
customerService.createCustomer(customer); // Create the new customer
return "redirect:/customers"; // Redirect to the list of customers after creation
}
@GetMapping("/{id}")
public String showCustomerDetail(@PathVariable String id, Model model) {
Optional customer = customerService.getCustomerById(id);
if (customer.isPresent()) {
model.addAttribute("customer", customer.get());
return "customer/customer-detail"; // Thymeleaf template for displaying customer details
}
return "redirect:/customers"; // Redirect if the customer is not found
}
@GetMapping("/{id}/edit")
public String showEditForm(@PathVariable String id, Model model) {
Optional customer = customerService.getCustomerById(id);
if (customer.isPresent()) {
model.addAttribute("customer", customer.get());
return "customer/customer-edit"; // Thymeleaf template for editing the customer
}
return "redirect:/customers"; // Redirect if the customer is not found
}
@PostMapping("/{id}/edit")
public String updateCustomer(@PathVariable String id, @ModelAttribute Customer customer) {
customerService.updateCustomer(id, customer); // Update the customer
return "redirect:/customers"; // Redirect to the list of customers after updating
}
@GetMapping("/{id}/delete")
public String deleteCustomer(@PathVariable String id) {
customerService.deleteCustomer(id); // Delete the customer
return "redirect:/customers"; // Redirect to the list of customers after deletion
}
}
[b]CustomerService.java[/b]
package com.bank.bankingapp.service;
import com.bank.bankingapp.model.Customer;
import com.bank.bankingapp.repository.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class CustomerService {
private final CustomerRepository customerRepository;
@Autowired
public CustomerService(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}
public List getAllCustomers() {
return customerRepository.findAll();
}
public Optional getCustomerById(String id) {
return customerRepository.findById(id);
}
public Customer createCustomer(Customer customer) {
return customerRepository.save(customer);
}
public Customer updateCustomer(String id, Customer customer) {
customer.setId(id);
return customerRepository.save(customer);
}
public void deleteCustomer(String id) {
customerRepository.deleteById(id);
}
}
Класс приложения приведен ниже.
package com.bank.bankingapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages = {"com.bank.bankingapp","com.bank.bankingapp.service","com.bank.bankingapp.controller","com.bank.bankingapp.model","com.bank.bankingapp.repository"})
public class BankingApplication {
public static void main(String[] args) {
SpringApplication.run(BankingApplication.class, args);
}
}
Приложение не запускается из-за проблемы с зависимостью компонента.
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customerController' defined in file [C:\Users\Debaditya Bhuyan\OneDrive\Downloads\Consultancy\Open Source Development\ja
va\banking-application\target\classes\com\bank\bankingapp\controller\CustomerController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.bank.bankingapp.service.CustomerService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.bank.bankingapp.service.CustomerService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Подробнее здесь: [url]https://stackoverflow.com/questions/79335375/failed-to-load-applicationcontext-caused-by-org-springframework-beans-factory-u[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия