当前位置: 首页 > 知识库问答 >
问题:

如何解决spring boot中所需bean的问题:?

向弘懿
2023-03-14

目前,我正在学习Spring启动课程。然而,从昨天开始,当我通过VS代码启动我的主类时,我就面临这个问题:“com.training.training.Service.ProduitServiceImpl中的字段pr需要一个无法找到的“com.training.training.Repos.ProduitRepository”类型的bean。”所以我请求一些帮助来解决这个问题。

以下是stacktrace:

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-12-31 14:12:25.347 ERROR 18056 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   : 

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

Description:

Field pr in com.training.training.Service.ProduitServiceImpl required a bean of type 'com.training.training.Repos.ProduitRepository' 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 'com.training.training.Repos.ProduitRepository' in your configuration.

以下是我的项目的特点:

  • Spring Boot版本2.6.2
  • Maven 3.8.3
  • JDK 8
  • MySQL数据库版本8.0

这是我的pom。xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.training</groupId>
    <artifactId>training</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>training</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>4.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

以下是构成后端的每个类的代码:

培训pplication.java(主班):

import com.training.training.Service.ProduitService;

import java.util.Date;

import com.training.training.Entities.Produit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TrainingApplication implements CommandLineRunner {
@Autowired
ProduitService produitService;

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

@Override
public void run(String... args) throws Exception {
    produitService.saveProduit(new Produit("PC Dell", 2600.0, new Date()));
    produitService.saveProduit(new Produit("PC Asus", 2800.0, new Date()));
    produitService.saveProduit(new Produit("Imprimante Epson", 900.0, new Date()));
}

}

ProduitController.java:

package com.training.training.Controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.training.training.Entities.Produit;
import com.training.training.Service.ProduitService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class ProduitController {

    @Autowired
    ProduitService ps;

    @RequestMapping("/showCreate")
    public String showCreate() {
        return "createProduit";
    }

    @PostMapping("/saveProduit")
    public String saveProduit(@ModelAttribute("Produit") Produit p, @RequestParam("dateCreationProduit") String date,
            ModelMap modelMap) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date dateCreation = sdf.parse(String.valueOf(date));
        p.setDateCreation(dateCreation);

        Produit savedProduit = ps.UpdateProduit(p);
        String msg = "produit enregistré avec Id " + savedProduit.getIdProduit();
        modelMap.addAttribute("msg", msg);
        return "createProduit";
    }

    @RequestMapping("/ListeProduits")
    public String listeProduits(ModelMap modelMap, @RequestParam(name = "page", defaultValue = "0") int page,
            @RequestParam(name = "size", defaultValue = "2") int size) {
        Page<Produit> listeProduits = ps.getAllProduitsParPage(page, size);
        modelMap.addAttribute("produits", listeProduits);
        modelMap.addAttribute("pages", new int[listeProduits.getTotalPages()]);
        modelMap.addAttribute("currentPage", page);
        return "listeProduits";
    }

    @DeleteMapping("/supprimerProduit")
    public String supprimerProduit(@RequestParam("id") Long id, ModelMap modelMap) {
        ps.deleteProduitById(id);
        List<Produit> listeProduits = ps.getAllProduit();
        modelMap.addAttribute("produits", listeProduits);
        return "listeProduits";
    }

    @RequestMapping("/modifierProduit")
    public String modifierProduit(@RequestParam("id") Long id, ModelMap modelMap) {
        Produit p = ps.getProduit(id);
        modelMap.addAttribute("produits", p);
        return "editerProduit";
    }

    @PostMapping("/modifierupdateProduit")
    public String updateProduit(@ModelAttribute("produit") Produit p, ModelMap modelMap, String date)
            throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d = sdf.parse(String.valueOf(date));
        p.setDateCreation(d);
        ps.UpdateProduit(p);
        List<Produit> listeProduits = ps.getAllProduit();
        modelMap.addAttribute("produits", listeProduits);
        return "listeProduits";
    }
}

普罗杜特。java(我的唯一实体):

package com.training.training.Entities;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Produit {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long idProduit;
    private String nomProduit;
    private Double prixProduit;
    private Date dateCreation;

    public Produit() {
        super();
    }

    public Produit(String nomProduit, Double prixProduit, Date dateCreation) {
        super();
        this.nomProduit = nomProduit;
        this.prixProduit = prixProduit;
        this.dateCreation = dateCreation;
    }

    public Long getIdProduit() {
        return idProduit;
    }

    public void setIdProduit(Long idProduit) {
        this.idProduit = idProduit;
    }

    public String getNomProduit() {
        return nomProduit;
    }

    public void setNomProduit(String nomProduit) {
        this.nomProduit = nomProduit;
    }

    public Double getPrixProduit() {
        return prixProduit;
    }

    public void setPrixProduit(Double prixProduit) {
        this.prixProduit = prixProduit;
    }

    public Date getDateCreation() {
        return dateCreation;
    }

    public void setDateCreation(Date dateCreation) {
        this.dateCreation = dateCreation;
    }

    @Override
    public String toString() {
        return "Produit [ idProduit = " + idProduit + ", nomProduit = " + nomProduit +
                ", prixProduit = " + prixProduit + ", dateCreation = " + dateCreation + "]";
    }
}

ProduitRepository.java(Produit实体的repos):

package com.training.training.Repos;

import com.training.training.Entities.Produit;

import org.springframework.data.jpa.repository.JpaRepository;

public interface ProduitRepository extends JpaRepository<Produit, Long> {

}

产品服务。JAVA

package com.training.training.Service;

import java.util.List;

import com.training.training.Entities.Produit;

import org.springframework.data.domain.Page;

public interface ProduitService {

    public Produit saveProduit(Produit p);

    public Produit UpdateProduit(Produit p);

    void deleteProduit(Produit p);

    void deleteProduitById(Long id);

    Produit getProduit(Long id);

    List<Produit> getAllProduit();

    public Page<Produit> getAllProduitsParPage(int page, int size);

}

ProduitServiceImpl.java(前一类ProduitService.java的实现):

package com.training.training.Service;

import java.util.List;

import com.training.training.Entities.Produit;
import com.training.training.Repos.ProduitRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

@Service
public class ProduitServiceImpl implements ProduitService {

    @Autowired
    ProduitRepository pr;

    @Override
    public Produit saveProduit(Produit p) {
        pr.save(p);
        return p;
    }

    @Override
    public Produit UpdateProduit(Produit p) {
        pr.save(p);
        return p;
    }

    @Override
    public void deleteProduit(Produit p) {
        pr.delete(p);
    }

    @Override
    public void deleteProduitById(Long id) {
        pr.deleteById(id);
    }

    @Override
    public Produit getProduit(Long id) {
        Produit p = pr.findById(id).get();
        return p;
    }

    @Override
    public List<Produit> getAllProduit() {
        List<Produit> l = pr.findAll();
        return l;
    }

    public Page<Produit> getAllProduitsParPage(int page, int size) {

        return pr.findAll(PageRequest.of(page, size));
    }

}

以下是构成我的前端的模板:

createProduit。html(用于创建产品并将其存储到数据库中的视图):

<!DOCTYPE html>
<html>
    <html xmlns:th="http://www.thymeleaf.org">
    <link rel="stylesheet" type="text/css" href="webjars/bootstrap/4.3.1/css/bootstrap.min.css"/>
<head>
    <meta charset="utf-8">
    <title>Ajouter Produit</title>
</head>

<body>
    <div class="container mt-5">
        <div class="card-body">
            <form action="saveProduit" method="post">
                <div class="form-group">
                    <label class="control-label">Nom Produit :</label>
                    <input type="text" name="nomProduit" class="form-control" />
                </div>
                <div class="form-group">
                    <label class="control-label">Prix Produit :</label>
                    <input type="text" name="prixProduit" class="form-control" />
                </div>
                <div class="form-group">
                    <label class="control-label">date création :</label>
                    <input type="date" name="dateCreationProduit" class="form-control" />
                </div>
                <div>
                    <button type="submit" class="btn btn-primary">Ajouter</button>
                </div>
            </form>
        </div>
        <p th:text="${msg}"></p>
        <br />
        <br />
        <a href="ListeProduits">Liste Produits</a>
    </div>
</body>

</html>

李斯特音乐学院。java(显示存储到DB中的所有产品列表的视图):

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<link rel="stylesheet" type="text/css" href="webjars/bootstrap/4.3.1/css/bootstrap.min.css" />

<head>
    <meta charset="utf-8">
    <title>Liste des Produits</title>
</head>

<body>
    <div class="container mt-5">
        <div class="card">
            <div class="card-header">
                Liste des Produits
            </div>
            <div class="card-body">
                <table class="table table-striped">
                    <tr>
                        <th>ID</th>
                        <th>Nom Produit</th>
                        <th>Prix</th>
                    </tr>
                    <tr th:each="p:${produits.content}">
                        <td th:text="${p.idProduit}"></td>
                        <td th:text="${p.nomProduit}"></td>
                        <td th:text="${p.prixProduit}"></td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
</body>

</html>

EditerProduit.html(用于更新最初存储到DB中的产品的视图):

<!DOCTYPE html>
<html>
    <html xmlns:th="http://www.thymeleaf.org">
    <link rel="stylesheet" type="text/css" href="webjars/bootstrap/4.3.1/css/bootstrap.min.css"/>
<head>
    <meta charset="utf-8">
    <title>Modifier un Produit</title>
</head>

<body>
    <div class="container mt-5">
        <div class="card-body">
            <form action="updateProduit" method="post">
                <div class="form-group">
                    <label class="control-label">ID Produit :</label>
                    <input type="text" name="idProduit" th:value="${produit.idProduit}" readonly class="form-control" />
                </div>
                <div class="form-group">
                    <label class="control-label">Nom Produit :</label>
                    <input type="text" name="nomProduit" th:value="${produit.nomProduit}" class="form-control" />
                </div>
                <div class="form-group">
                    <label class="control-label">Prix Produit :</label>
                    <input type="text" name="prixProduit" th:value="${produit.prixProduit}" class="form-control" />
                </div>
                <div class="form-group">
                    <label class="control-label"> Date création :</label>
                    <fmt:formatDate pattern="yyyy-MM-dd" th:value="${produit.dateCreation}" var="formatDate"/>
                    <input type="date" name="date" th:value="${formatDate}" class="form-control" />
                </div>
                <div>
                    <button type="submit" class="btn btn-primary">Modifier</button>
                </div>
            </form>
        </div>
        <br />
        <br />
        <a href="ListeProduits">Liste Produits</a>
    </div>
</body>

</html>

这里我的文件架构:

任何帮助都将不胜感激。

最好的问候,

YT

共有1个答案

苍阳成
2023-03-14

你能分享你的项目结构吗?否则,您需要确保您的界面与TrainingApplication在同一个包中,并将@ComponentScan添加到TrainingApplication。

 类似资料:
  • 我是Springboot的新手,我通过Sping的教程和“https://spring.io/guides”指南来学习。 现在我试图理解并重做教程:“使用MySQL访问数据” 不幸的是,我在Mavenbuild期间出错: 启动ApplicationContext时出错。要显示自动配置报告,请在启用“调试”的情况下重新运行应用程序。2017-12-07 10:26:42.708错误8100---[m

  • 当我尝试运行应用程序时,它工作正常。但是当我构建签名apk时,出现了错误 失败:构建失败,出现异常。 问题:任务“:app:lintVitalRelease”的执行失败 无法解析配置“:image_picker_android:调试单元测试运行时类路径”的所有项目。无法转换 bcprov-jdk15on-1.68.jar (org.bouncycastle:bcprov-jdk15on:1.68)

  • 我有很多表,但它们有共同的自动增量。例如,我创建了我的第一个用户,它的id为1,然后我创建了一条消息,它的id为2,然后我创建了一条对消息的注释,它的id为3,但它的id应该为1,因为我没有任何其他注释或消息 我的用户: 我的信息: 我的评论是: 我将感谢任何帮助。

  • 主要内容:1.缓存穿透,2.缓存击穿,3.缓存雪崩缓存穿透 缓存击穿 缓存雪崩 1.缓存穿透 缓存穿透指的是一个缓存系统无法缓存某个查询的数据,从而导致这个查询每一次都要访问数据库。 常见的Redis缓存穿透场景包括: 查询一个不存在的数据:攻击者可能会发送一些无效的查询来触发缓存穿透。 查询一些非常热门的数据:如果一个数据被访问的非常频繁,那么可能会导致缓存系统无法处理这些请求,从而造成缓存穿透。 查询一些异常数据:这种情况通常发生在数据服务出

  • 抱歉打扰你们了。我知道,这个问题已经问了好几遍了。然而,我就是无法解决我的问题。 所以,我一直在尝试创建一个网球计分系统,当你点击两个按钮之一,赢按钮或输按钮时,就会显示出分数。我有一个按钮,他们可以在那里添加他们的名字到计分系统。当一个选手赢了两盘,比赛就结束了。然后我试着印上他们的名字,上面写着,____赢了比赛。当我尝试使用打印它们名称的变量时,我得到的结果是:[objectHTMLButt

  • 问题内容: IntelliJ无法解析用webpack require调用的javascript模块,这些模块不在目录中 想象一下这个项目结构: 这是我的webpack配置 这就是我使用webpack的需求 因此,这在我的应用程序中完美运行,并且IntelliJ对“反应/附加组件”感到满意,如何理解导航源,代码完成以及“组件/一个”和“实用程序/工具”的文档查找? 到目前为止,我已经尝试过: 在sr