You need to enable JavaScript to run this app. 如何在Gradle Spring Boot项目中连接PostgreSQL并解决空指针异常
优惠活动
大模型
产品
解决方案
定价
更多

如何在Gradle Spring Boot项目中连接PostgreSQL并解决空指针异常

Spring Boot 连接PostgreSQL触发空指针异常的排查修复

直接触发报错的根因

空指针栈指向PersonService.create方法内的personRepository.save()调用,本质是personRepository属性为null。
这个问题完全来自控制器的写法:在PostgresdemoApplication的create接口中用new PersonService()手动创建了Service实例,这个实例不属于Spring IoC容器管理范围,容器根本不会对该实例上@Autowired修饰的personRepository属性执行注入操作,最终调用方法时直接触发空指针。

逐步骤修复方案

  • 修正控制器的Service获取方式
    删除手动new的逻辑,改为从Spring容器中注入已经被管理的PersonService实例。修正后代码:
    @RestController
    @SpringBootApplication
    public class PostgresdemoApplication {
        // 注入容器内的PersonService实例
        @Autowired
        private PersonService personService;
    
        public static void main(String[] args) {
            SpringApplication.run(PostgresdemoApplication.class, args);
        }
        @GetMapping("/hello")
        public String hello(@RequestParam(value = "name", defaultValue = "world") String name){
            return String.format("Hello, %s", name);
        }
        @GetMapping("/create")
        public Person create(@RequestParam int id, @RequestParam String name){
            // 调用注入的Service实例完成业务逻辑
            return personService.create(id, name);
        }   
    }
    
  • 修复实体类的JPA规范问题,避免启动/持久化阶段报错
    当前Person实体类存在两处不符合JPA规范的问题,即使解决了空指针问题,后续也会触发持久层报错:
    1. JPA要求实体类必须具备无参构造方法,当前类只定义了带参构造,会导致Hibernate无法实例化实体
    2. 主键id未配置生成策略,会导致存储时主键赋值逻辑异常
      修正后的实体类代码:
    @Entity
    @Table(name = "person")
    @Data
    public class Person {
        @Id
        @NotNull
        // 手动传入id的场景使用ASSIGNED策略,如果使用PG自增主键可替换为GenerationType.IDENTITY
        @GeneratedValue(strategy = GenerationType.ASSIGNED)
        private int id;
        @NotNull
        private String name;
    
        // 必须补充无参构造
        public Person(){}
    
        public Person(int id, String name){
            this.setId(id);
            this.setName(name);
        }
    }
    
  • 清理冗余的Gradle依赖
    当前依赖中同时引入spring-boot-starter-data-jdbc、spring-boot-starter-jdbc、spring-boot-starter-data-jpa,其中spring-boot-starter-data-jpa已经自动包含了JDBC相关的核心依赖,冗余依赖可能引发类路径冲突,可删除多余配置:
    修正后的build.gradle依赖块:
    dependencies {
        implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
        implementation 'org.springframework.boot:spring-boot-starter-web'
        compileOnly 'org.projectlombok:lombok'
        runtimeOnly 'org.postgresql:postgresql'
        annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
        annotationProcessor 'org.projectlombok:lombok'
        testImplementation 'org.springframework.boot:spring-boot-starter-test'
    }
    
  • 补充JPA自动建表配置
    在application.properties中新增配置,让Hibernate自动根据实体类结构更新数据库表,避免手动建表的格式不一致问题:
    spring.jpa.show-sql = true
    spring.datasource.username = postgres
    spring.datasource.password = password
    spring.datasource.driverClassName = org.postgresql.Driver
    spring.datasource.url = jdbc:postgresql://localhost:5432/postgres
    # 新增:自动根据实体类更新表结构
    spring.jpa.hibernate.ddl-auto = update
    

修复后验证

重启Spring Boot应用,再次访问http://localhost:8080/create?id=7&name=name接口,可正常完成数据存储,无空指针报错。


内容的提问来源于stack exchange,提问作者YeKc1M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.17 17:27:03