Spring Boot JPA项目entityManagerFactory Bean缺失问题求助
User实体类
package com.userproject.Entities; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; @Entity @Table(name = "userservice") public class User { @Id @Column(name="userID") int userId; @Column(name="username") String username; @Column(name="age") int age; public User(int userId, String username, int age) { super(); this.userId = userId; this.username = username; this.age = age; } public User() { super(); // TODO Auto-generated constructor stub } @Override public String toString() { return "User [userId=" + userId + ", username=" + username + ", age=" + age + "]"; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
UserRepository接口
package com.userproject.dao; import org.springframework.data.jpa.repository.JpaRepository; import com.userproject.Entities.User; public interface UserRepository extends JpaRepository<User, Integer> { public User findById(int id); }
UserService类
package com.userproject.Service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.userproject.Entities.User; import com.userproject.dao.UserRepository; @Service public class UserService { @Autowired private UserRepository userRepository; public User addUser(User usr) { User savedUser = this.userRepository.save(usr); return savedUser; } public List<User> getAllInfo(){ Iterable<User> allUsers = this.userRepository.findAll(); return (List<User>)allUsers; } public User getUser(int usrId) { User usr = this.userRepository.findById(usrId); if (usr == null) throw new NullPointerException(); return usr; } }
UserController类
package com.userproject.Controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; 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.userproject.Entities.User; import com.userproject.Service.UserService; @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService service; @PostMapping("/add") public ResponseEntity<User> addUser(@RequestBody User u){ try { User addUser = this.service.addUser(u); return ResponseEntity.ok(addUser); } catch(Exception e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } @GetMapping("/{id}") public ResponseEntity<User> getUserById(@PathVariable("id") int userID){ try { User u = this.service.getUser(userID); return ResponseEntity.ok(u); } catch(NullPointerException e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); } catch (Exception e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } @GetMapping("/all") public ResponseEntity<List<User>> getAllUsers(){ try { return ResponseEntity.ok(this.service.getAllInfo()); } catch(Exception e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } }
主应用类
package com.userproject; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @EnableJpaRepositories("com.userproject.dao") @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class }) public class UserProjectApplication { public static void main(String[] args) { SpringApplication.run(UserProjectApplication.class, args); } }
application.properties配置
spring.jpa.database=mysql spring.datasource.username=***** spring.datasource.password=***** spring.datasource.url=jdbc:mysql://*******:3306/practice spring.datasource.driver-class-name= com.mysql.jdbc.Driver spring.jooq.sql-dialect = org.hibernate.dialect.MySQL57Dialect spring.jpa.hibernate.ddl-auto= update
报错信息
Description:
Field userRepository in com.userproject.Service.UserService required a bean named 'entityManagerFactory' 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 named 'entityManagerFactory' in your configuration.
问题补充
- 移除
@SpringBootApplication中的exclude参数,会提示数据源无法配置,原因是URL缺失 - 移除
@EnableJpaRepositories,则提示Service类中的userRepository字段无法配置 - 预期Spring Boot能自动生成Repository代理类完成注入,但实际失败
解决方案
1. 移除错误的自动配置排除项
主类中排除DataSourceAutoConfiguration.class会导致Spring无法自动创建数据源及依赖的entityManagerFactory(JPA核心组件),这是报错的根本原因,必须删除该排除项:
@SpringBootApplication public class UserProjectApplication { // ... 主方法不变 }
2. 修复数据源配置问题
移除排除项后若提示URL缺失,检查以下几点:
- 确保
spring.datasource.url格式正确,示例:jdbc:mysql://localhost:3306/practice?useSSL=false&serverTimezone=UTC - 删除配置项中等号后的多余空格,比如
spring.datasource.driver-class-name= com.mysql.jdbc.Driver改为spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver(推荐使用新版驱动类) - 确认数据库服务正常启动,账号密码拥有目标数据库的访问权限
3. 删除重复的Repository方法
JpaRepository已自带findById(Integer id)方法(返回Optional<User>),自定义的findById(int id)会冲突,删除该方法后修改Service逻辑:
// UserService中getUser方法修改为 public User getUser(int usrId) { return this.userRepository.findById(usrId) .orElseThrow(() -> new NullPointerException()); }
4. 简化主类配置
主类包com.userproject是所有子包的父包,@SpringBootApplication会自动扫描所有子包组件,包括Repository,可移除@EnableJpaRepositories注解。
5. 优化类型转换
Service中getAllInfo方法无需强转,直接返回:
public List<User> getAllInfo(){ return this.userRepository.findAll(); }
内容的提问来源于stack exchange,提问作者Srinjit Bhattacharyya

