如何跨 spring boot 共享 ArrayList

问题描述 投票:0回答:2

我有一个使用 aws kinesis stream 的 java 应用程序。

在应用程序中,我通过kinesis stream实时获取学生数据,我必须根据学生id做一些动作。

我需要从数据库中查询学生列表,并且来自运动流的每个学生都需要检查学生是否在列表中。

但是我只想查询一次学生列表到数据库,因为这是要求之一。

最重要的是,我想在应用程序启动后立即进行查询;这样,如果查询失败,我们也可以使应用程序失败。换句话说,如果查询不成功,应用程序不应运行。

这就是我想做的

@SpringBootApplication
@EnabledScheduling
@EnableCaching
@Configuration
class Application implements CommandLineRuner {

  @Autowired
  RestTemplate restTemplate

  @Autowired
  List<Student> students

  static void main(String[] args) {
    SpringApplication app = new SpringApplication(Application);
    app.webApplicationType = WebApplicationType.NONE;
    app.run(args)
  }

  @Overrde
  void run(String... args) thows Exception {
    try {
      // make a request
      List<Student> people = this.restTemplate.exchange("https://some.url.com", ...other params)
      this.students = people

      // running kcl worker
      KclConsumer.kclWorker.run()
    } catch (Exception ex) {
      ....
    }
  }
}
@Service
class SomeService {

  @Autowired
  RestTemplate restTemplate

  @Autowired
  List<Student> students

  void func(Student id) {
    this.students.each {
      if(id == it.id) {
        println("found you")
        return;
      }
    }
    println("not found")
  }
}

我已经尝试创建 bean 并按如下方式在项目中共享,但它似乎不起作用......

class SomeConfig {
  @Bean
  List<Student> students() {
    return new ArrayList<>();
  }
}

我猜我使用 bean 的方式是错误的。 有人可以帮我处理我的代码吗? 提前谢谢你

java spring spring-boot javabeans autowired
2个回答
0
投票

理论上,在bean中提供它应该可以,但是你应该确保在bean中初始化它的数据。

@Bean
public List<Student> getStudents() {
    RestTemplate restTemplate = new RestTemplate();
    List<Student> people = restTemplate.exchange("https://some.url.com", ...other params);
    return people;
}

默认情况下这个 bean 应该是单例的,所以它应该是在其他任何地方提供的相同列表

List<Student>
被注入(通过构造函数注入或使用
@Autowired

如果你需要在其他地方使用 RestTemplate,你也可以把它做成一个 bean,我相信你已经做过了,然后通过构造函数注入它。

@Bean
public List<Student> getStudents(RestTemplate restTemplate) {
    List<Student> people = restTemplate.exchange("https://some.url.com", ...other params);
    return people;
}

编辑:我做了更多的研究,它似乎使列表可访问,您可能需要使用

@Resource
而不是
@Autowired
在这里建议 如何在spring中定义一个list bean


0
投票

不要做

List<Student>
的豆子。用
public List<Student> getStudents()
方法创建一个业务类——这个类应该是一个bean。

© www.soinside.com 2019 - 2024. All rights reserved.