org.springframework.beans.factory.UnsatisfiedDependencyException: ошибка при создании компонента с именем customerController: неудовлетворенная зависимость - PullRequest
0 голосов
/ 21 апреля 2020

Приложение

@SpringBootApplication

@ EnableConfigurationProperties (StorageProperties.class) publi c Класс Application {{1006 *

public static void main(String[] args) {

    ApplicationContext ctx = SpringApplication.run(Application.class, args);}}

** FileResponse **

public class FileResponse {
private String name;
private String uri;
private String type;
private long size;

public FileResponse(String name, String uri, String type, long size) {
    this.setName(name);
    this.setUri(uri);
    this.setType(type);
    this.setSize(size);
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getUri() {
    return uri;
}

public void setUri(String uri) {
    this.uri = uri;
}

public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}

public long getSize() {
    return size;
}

public void setSize(long size) {
    this.size = size;
}

// getters and setters removed for the sake of brevity

}

StorageProperties

@ConfigurationProperties(prefix = "storage")

publi c Класс StorageProperties {

private String location;

public String getLocation() {
    return location;
}

public void setLocation(String location) {
    this.location = location;
}

} ​​

StorageService

@Service 

publi c интерфейс StorageService {

void init();

String store(MultipartFile file);

Stream<Path> loadAll();

Path load(String filename);

Resource loadAsResource(String filename);

void deleteAll();

}

** FileSystemStorageService **

@ Service publi c Класс FileSystemStorageService реализует StorageService {

private final Path rootLocation;

@Autowired
public FileSystemStorageService(StorageProperties properties) {
    this.rootLocation = Paths.get(properties.getLocation());
}

@Override
@PostConstruct
public void init() {
    try {
        Files.createDirectories(rootLocation);
    } catch (IOException e) {
        throw new StorageException("Could not initialize storage location", e);
    }
}

@Override
public String store(MultipartFile file) {
    String filename = StringUtils.cleanPath(file.getOriginalFilename());
    try {
        if (file.isEmpty()) {
            throw new StorageException("Failed to store empty file " + filename);
        }
        if (filename.contains("..")) {
            // This is a security check
            throw new StorageException(
                    "Cannot store file with relative path outside current directory "
                            + filename);
        }
        try (InputStream inputStream = file.getInputStream()) {
            Files.copy(inputStream, this.rootLocation.resolve(filename),
                    StandardCopyOption.REPLACE_EXISTING);
        }
    }
    catch (IOException e) {
        throw new StorageException("Failed to store file " + filename, e);
    }

    return filename;
}

@Override
public Stream<Path> loadAll() {
    try {
        return Files.walk(this.rootLocation, 1)
                .filter(path -> !path.equals(this.rootLocation))
                .map(this.rootLocation::relativize);
    }
    catch (IOException e) {
        throw new StorageException("Failed to read stored files", e);
    }

}

@Override
public Path load(String filename) {
    return rootLocation.resolve(filename);
}

@Override
public Resource loadAsResource(String filename) {
    try {
        Path file = load(filename);
        Resource resource = new UrlResource(file.toUri());
        if (resource.exists() || resource.isReadable()) {
            return resource;
        }
        else {
            throw new FileNotFoundException(
                    "Could not read file: " + filename);
        }
    }
    catch (MalformedURLException e) {
        throw new FileNotFoundException("Could not read file: " + filename, e);
    }
}

@Override
public void deleteAll() {
    FileSystemUtils.deleteRecursively(rootLocation.toFile());
}

} ** FileNotFoundException **

@ResponseStatus(HttpStatus.NOT_FOUND)

publi c Класс FileNotFoundException расширяет StorageException {

public FileNotFoundException(String message) {
    super(message);
}

public FileNotFoundException(String message, Throwable cause) {
    super(message, cause);
}

}

StorageException

publi c Класс StorageException расширяет RuntimeException {

public StorageException(String message) {
    super(message);
}

public StorageException(String message, Throwable cause) {
    super(message, cause);
}

}

page HTML `` Company Lo go Просмотр ... Попробуйте выбрать файл text для загрузки. Название компании Адрес компании Телефон компании Имя CIO Электронная почта CIO Телефон CIO Техническое имя Техническая электронная почта Технический телефон Страна Компания Городская компания Промышленность VIP
Сохранить Annuler

CustomerController

@Autowired
private CustomerRepository customerrepository; 

@RequestMapping(value="/customer_manage")
public String AllCustomer(Model model, Customer customer) {

    List<Customer> custs = customerrepository.findAll();
    model.addAttribute("cust", custs);
    model.addAttribute("customer", new Customer());
    model.addAttribute("totalCustomer", custs.size());

    return "customer_manage";
}
 @Autowired
 private StorageService storageService;

    public CustomerController(StorageService storageService) {
        this.storageService = storageService;
    }

    @GetMapping("/")
    public String listAllFiles(Model model) {

        model.addAttribute("files", storageService.loadAll().map(
                path -> ServletUriComponentsBuilder.fromCurrentContextPath()
                        .path("/download/")
                        .path(path.getFileName().toString())
                        .toUriString())
                .collect(Collectors.toList()));

        return "listFiles";
    }

    @GetMapping("/download/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {

        Resource resource = storageService.loadAsResource(filename);

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
    }

    @PostMapping("/upload-file")
    @ResponseBody
    public FileResponse uploadFile(@RequestParam("file") MultipartFile file) {
        String name = storageService.store(file);

        String uri = ServletUriComponentsBuilder.fromCurrentContextPath()
                .path("/download/")
                .path(name)
                .toUriString();

        return new FileResponse(name, uri, file.getContentType(), file.getSize());
    }
   /* @PostMapping("/upload-multiple-files")
    @ResponseBody
    public List<FileResponse> uploadMultipleFiles(@RequestParam("files") MultipartFile[] files) {
        return Arrays.stream(files)
                .map(file -> uploadFile(file))
                .collect(Collectors.toList());
    } */

@RequestMapping(value="/SaveCustomer" , method= RequestMethod.POST)
private String SaveCustomer(@Valid Customer addCust, BindingResult bindingResult) {//, @RequestParam(name="picture")MultipartFile file
        addCust.setStatus("Actif");
        customerrepository.save(addCust);

    return "redirect:/customer_manage"; 
}

@RequestMapping(value ="updateCustomerform" )
private String updateCustomerform( Model model, Integer id ) {
    Customer customer = customerrepository.getOne(id);
    model.addAttribute("customer",customer);
    System.out.println(customer.getName());
    return "updateCustomerForm";            
}

@RequestMapping(value = "/editCustomer",method= RequestMethod.POST)
private String updateCustomer(@Valid Customer addCust, BindingResult bindingResult) {//, @RequestParam(name="picture")MultipartFile file
        addCust.setStatus("Actif");
        customerrepository.save(addCust);
    return "redirect:/customer_manage";
}

@RequestMapping(value ="/detailCustomer")
public String detailCustomer( Model model, Integer id ) {
    Customer customer = customerrepository.getOne(id);
     model.addAttribute("customer",customer);
     System.out.println(customer.getName());    
        return "detailCust";
}

@RequestMapping(value ="/archiverCustomer" )
private String archiverCustomer( Model model, Integer id ) {
    Customer Cust = customerrepository.getOne(id);
    Cust.setStatus("Archived");
    customerrepository.save(Cust);

    return "redirect:/customer_manage";         
}

}

application.properties

`spring.servlet.multipart.max-file-size = 10 МБ

spring.servlet.multipart.max-request-size = 10 МБ enter code here

storage.location = ./uploads `

ошибка org.springframework.beans.factory.UnsatisfiedDependencyException: Ошибка создания компонента с именем 'customerController', определенным в файле [D: \ STAGEPFEPowerM \ Spring \ TEST5 \ PMP2. 2 \ target \ classes \ com \ example \ demo \ controllers \ CustomerController.class]: неудовлетворенная зависимость, выраженная через параметр конструктора 0; вложенным исключением является org.springframework.beans.factory.BeanCreationException: ошибка создания компонента с именем fileSystemStorageService, определенным в файле [D: \ STAGEPFEPowerM \ Spring \ TEST5 \ PMP2.2 \ target \ classes \ com \ example \ demo \ exception \ FileSystemStorageService.class]: не удалось создать экземпляр компонента с помощью конструктора; вложенным исключением является org.springframework.beans.BeanInstantiationException: не удалось создать экземпляр [com.example.demo.exception.FileSystemStorageService]: конструктор вызвал исключение; вложенное исключение: java .nio.file.InvalidPathException: конечный символ <> в индексе 18: ./uploads

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...