繁体   English   中英

考虑在配置中定义类型为'com.ensat.services.ProductService'的bean

[英]Consider defining a bean of type 'com.ensat.services.ProductService' in your configuration

我有

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
@ComponentScan(basePackages = {"hello","com.ensat.controllers"})
@EntityScan("com.ensat.entities")
public class Application extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }

}

ProductController.java

package com.ensat.controllers;

import com.ensat.entities.Product;
import com.ensat.services.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Product controller.
 */
@Controller
public class ProductController {

    private ProductService productService;

    @Autowired
    public void setProductService(ProductService productService) {
        this.productService = productService;
    }

    /**
     * List all products.
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/products", method = RequestMethod.GET)
    public String list(Model model) {
        model.addAttribute("products", productService.listAllProducts());
        System.out.println("Returning rpoducts:");
        return "products";
    }

    /**
     * View a specific product by its id.
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("product/{id}")
    public String showProduct(@PathVariable Integer id, Model model) {
        model.addAttribute("product", productService.getProductById(id));
        return "productshow";
    }

    // Afficher le formulaire de modification du Product
    @RequestMapping("product/edit/{id}")
    public String edit(@PathVariable Integer id, Model model) {
        model.addAttribute("product", productService.getProductById(id));
        return "productform";
    }

    /**
     * New product.
     *
     * @param model
     * @return
     */
    @RequestMapping("product/new")
    public String newProduct(Model model) {
        model.addAttribute("product", new Product());
        return "productform";
    }

    /**
     * Save product to database.
     *
     * @param product
     * @return
     */
    @RequestMapping(value = "product", method = RequestMethod.POST)
    public String saveProduct(Product product) {
        productService.saveProduct(product);
        return "redirect:/product/" + product.getId();
    }

    /**
     * Delete product by its id.
     *
     * @param id
     * @return
     */
    @RequestMapping("product/delete/{id}")
    public String delete(@PathVariable Integer id) {
        productService.deleteProduct(id);
        return "redirect:/products";
    }

}

ProductService.java

package com.ensat.services;

import com.ensat.entities.Product;

public interface ProductService {

    Iterable<Product> listAllProducts();

    Product getProductById(Integer id);

    Product saveProduct(Product product);

    void deleteProduct(Integer id);

}

ProductServiceImpl.java

package com.ensat.services;

import com.ensat.entities.Product;
import com.ensat.repositories.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Product service implement.
 */
@Service
public class ProductServiceImpl implements ProductService {

    private ProductRepository productRepository;

    @Autowired
    public void setProductRepository(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    @Override
    public Iterable<Product> listAllProducts() {
        return productRepository.findAll();
    }

    @Override
    public Product getProductById(Integer id) {
        return productRepository.findOne(id);
    }

    @Override
    public Product saveProduct(Product product) {
        return productRepository.save(product);
    }

    @Override
    public void deleteProduct(Integer id) {
        productRepository.delete(id);
    }

}

这是我的错误:

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of method setProductService in com.ensat.controllers.ProductController required a bean of type 'com.ensat.services.ProductService' that could not be found.


Action:

Consider defining a bean of type 'com.ensat.services.ProductService' in your configuration.

我有完整的日志: https//gist.github.com/donhuvy/b918e20eeeb7cbe3c4be4167d066f7fd

这是我的完整源代码https://github.com/donhuvy/accounting/commit/319bf6bc47997ff996308c890eba81a6fa7f1a93

如何修复错误?

bean不是由Spring创建的,因为componentScan属性错过了ProductServiceImpl所在的包。

此外,还缺少@EnableJpaRepositories 因此,Spring无法连接您的存储库。

@SpringBootApplication
@ComponentScan(basePackages = {"hello","com.ensat.controllers"})
@EntityScan("com.ensat.entities")

应该替换为:

@SpringBootApplication
@ComponentScan(basePackages = {"hello","com.ensat.controllers", "com.ensat.services";
})
@EntityScan("com.ensat.entities")
@EnableJpaRepositories("com.ensat.repositories")

它将解决您的问题,但这种做法违反了Spring和Spring Boot的配置优势的约定。

如果Application bean类位于所有其他bean类所属的父包或它的子包中,则不再需要指定这两个注释:

@ComponentScan(basePackages = {"hello","com.ensat.controllers"})
@EntityScan("com.ensat.entities")

@SpringBootApplication类中。

例如,在com.ensat包中移动Application并将所有bean移动到此包或它的子包中都将解决配置问题并减轻配置。

package com.ensat;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application extends SpringBootServletInitializer {
    ...
}

为什么?

因为@SpringBootApplication已包含它们(以及更多):

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
        @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
        @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {

但是,它使用当前类的包作为basePackage值来发现bean /实体/存储库等...

文档提到了这一点。

这里

许多Spring Boot开发人员总是使用@Configuration,@ EnableAutoConfiguration和@ComponentScan注释其主类。 由于这些注释经常一起使用(特别是如果您遵循上面的最佳实践),Spring Boot提供了一个方便的@SpringBootApplication替代方案。

@SpringBootApplication注释等同于使用@ Configuration,@ EnableAutoConfiguration和@ComponentScan及其默认属性

这里讨论@EnableAutoConfiguration提供的实体发现77.3使用Spring Data存储库点

Spring Boot会根据找到的@EnableAutoConfiguration尝试猜测@Repository定义的位置。 要获得更多控制,请使用@EnableJpaRepositories批注(来自Spring Data JPA)。

我遇到了这个错误,我花了整整一个下午才弄清楚。 我已经检查了每个stackoverflow帖子, spring.io docs,与此问题相关的github问题,并且没有一个答案可以解决错误。

总之,我试过:

  1. 重构和重命名我的包和类
  2. 定义备用类以进行配置
  3. 删除或重制错误的类
  4. 尽可能彻底地注释我的课程
  5. 完全定义类
  6. 创建多个代码实现到@Autowire我的存储库
  7. 绝望地把我的头撞在墙上 - 好吧,我可能已经超越了这一点

鉴于我有两个存储库,其中没有一个被@ComponentScan@EntityScan注释识别。 总而言之,我无法使用它们实例化或执行任何操作。

对我来说诀窍是什么,如果你已经筋疲力尽,我建议你做什么呢

  1. 仔细检查pom.xml中的项目依赖项 该错误可能与您的代码无关(因为它不在我的代码中)。
  2. 如果您的依赖项是正确的,那么使用修改后的pom.xml 创建一个新的Maven项目
  3. 更新您的Maven依赖项 值得一提的是,我通过我的IDE(Eclipse + Spring Tool Suite)完成了这项工作(我不相信Spring Tool Suite在更新方面做了很大的改动)4。 构建你的软件包以便它们遵循最佳实践(有这个一个不错的文章在这里 。)
  4. 然后,小心地将文件迁移回来。 从bean开始,执行程序,检查错误; 然后是存储库,执行,测试; 任何启动脚本; 然后控制器等。花点时间确保一切正常。

有时调试这些应用程序会非常痛苦。 我有我的份额。 我希望它有所帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM