我正在尝试运行Spring开发的Web应用程序,但出现以下错误。
我的文件夹结构如下。
这是我的PersonRepositary.java代码,它位于存储库文件夹中。
package com.travelx.travelx.repositary;
import org.springframework.data.repository.CrudRepository;
import com.travelx.travelx.models.Person;
public interface PersonRepositary extends CrudRepository<Person, Integer> {
}
后面是ac文件夹中的RegisterController.java文件。
package com.travelx.travelx.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.travelx.travelx.models.Person;
import com.travelx.travelx.repositary.PersonRepositary;
@RestController
@RequestMapping("register")
public class RegisterController {
@Autowired
private PersonRepositary personRepositary;
@PostMapping("login")
public String registerPerson(@RequestBody Person person) {
personRepositary.save(person);
return "You are Registered!";
}
}
下面是控制器中的TravelXApplication.java文件。
package com.travelx.travelx.controllers;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication
@ComponentScan
@EntityScan
@EnableJpaRepositories
public class TravelxApplication {
public static void main(String[] args) {
SpringApplication.run(TravelxApplication.class, args);
}
}
我正在尝试制作一个网页,一个人可以在该网页上注册。在这里,我使用xampp作为处理后端的平台。如图所示,控制器,存储库和模型在单独的文件夹中实现。我是Spring的新手。因此,无论我多么努力地找到问题所在,我似乎都找不到。有人可以帮我吗?
-------------- UPDATE ------------------
我已经将TravelXApplication.java移到了com.travelx.travelx,现在这个错误已经消失了。Spring可以正常工作。但是,当我打开表单,插入数据并尝试保存它时,浏览器给我以下错误。
我该如何解决?
答案 0 :(得分:1)
您的PersonRepositary
在您的Spring上下文中未注册为bean。实际上,这意味着Spring无法将其注入到您的RegisterController
中。
我怀疑@EnableJpaRepositories
,@EntityScan
和@ComponentScan
在您的主应用程序类中是不必要的,实际上导致了Spring自动配置被覆盖。尝试从TravelxApplication
中删除这三个注释。
这是answer为何无需注释也可以正常工作的原因。
更新:刚注意到您的TravelxApplication
位于 controllers 包中,但是它对存储库没有可见性。确保将主类移至com.travelx.travelx
包中。