Spring Boot调用repository.saveAll报错:Cannot resolve symbol 'repository'
问题解决:Cannot resolve symbol 'repository'
问题原因
你在StudentConfig的commandLineRunner方法里直接使用repository变量,但该变量既未定义也未通过Spring注入,导致IDE无法识别。
解决方案
Spring支持在@Bean标注的方法中直接注入依赖,只需将StudentRepository作为commandLineRunner方法的参数,Spring会自动完成注入。修改后的代码如下:
修改后的StudentConfig代码
package com.example.demo.student; import org.springframework.boot.CommandLineRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.time.LocalDate; import java.time.Month; import java.util.List; @Configuration public class Studentconfig { @Bean CommandLineRunner commandLineRunner(StudentRepository repository) { // 注入StudentRepository作为方法参数 return args -> { Student mariam = new Student( "Mariam", "mariam.jamal@gmail.com", LocalDate.of(2000, Month.JANUARY, 5) ); Student alex = new Student( "Alex", "alex@gmail.com", LocalDate.of(2004, Month.JANUARY, 5) ); repository.saveAll( List.of(mariam, alex) ); }; } }
补充说明
- 你的
StudentRepository已经添加了@Repository注解,Spring会自动将其纳入容器管理,无需额外添加其他注解。 - 这种通过方法参数注入依赖的方式是Spring推荐的用法,尤其适合在
@Bean方法中使用。
内容的提问来源于stack exchange,提问作者RedRum
相关产品推荐
相关产品推荐

