无法在 Spring Boot 中自动装配对象列表 [英] Can't Autowire List of objects in Spring boot
问题描述
我正在 Spring Boot 中创建一个 REST 服务.我正在创建一个对象列表(List
)作为配置类中的 bean 并尝试通过自动连接在服务类中使用,但我总是得到空列表,我尝试过构造函数注入以及但不工作.下面是代码,
I am creating a REST service in Spring boot. I am creating a list of objects(List<Record>
) as bean in config class and trying to use in service class by auto wiring, but I am always getting empty list, I have tried in constructor injection as well but not working. Below is the code,
主应用
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
REST 控制器
@RestController
@RequestMapping("/v1")
public class RestController {
@Autowired
private Service service;
服务
@Service
public class ServiceImpl implements Service {
@Autowired
public ServiceImpl(List<Record> records) {
System.out.println(records); //------------------->getting empty list [null]
data = new Data();
customers = Arrays.asList("John", "James", "Calvin");
}
配置类
@Configuration
public class AppConfig {
@Bean
public List<Record> records(){
List<Record> records = new ArrayList<Record>();
records.add(new Record("d"));
return records;
}
}
我找不到我做错了什么,请指教.
I can't find what I am doing wrong please advise.
项目文件夹结构
推荐答案
以下代码对我有用:
public class Record {
private final String s;
public Record(String s) {
this.s = s;
}
@Override
public String toString() {
return "Record{" +
"s='" + s + '\'' +
'}';
}
}
@Service
public class RecordService {
private final List<Record> recordList;
public RecordService(List<Record> recordList) {
this.recordList = recordList;
}
}
@Configuration
public class MyConfiguration {
@Bean
public List<Record> recordList() {
return Arrays.asList(new Record("a"), new Record("b"));
}
}
一切都按预期注入(spring boot version 2.3.1.RELEASE)
Everything gets injected as expected (spring boot version 2.3.1.RELEASE)
从问题来看,您似乎做对了一切,我基本上只是确认 spring/spring boot 可以处理这样的情况.您使用哪个 spring boot/spring 版本?
From the question it looks like you did everything right and I basically just confirmed that spring / spring boot can deal with cases like this. Which spring boot/spring version do you use?
这篇关于无法在 Spring Boot 中自动装配对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!