我正在使用 Spring Boot 开发我的第一个 REST API。这是一项家庭作业,但我扩展了它以了解更多信息。 实际上, Controller 的代码是这样的:
@RestController
@EnableAutoConfiguration
@EnableSwagger2
@Api(description = "API pour l'ensemble des opérations")
public class MyServiceController {
public static void main(String[] args) throws Exception {
SpringApplication.run(MyServiceController.class, args);
}
private Centers centers;
public MyServiceController() {
Cage usa = new Cage(
"usa",
new Position(49.305d, 1.2157357d),
25,
new LinkedList<>(Arrays.asList(
new Animal("Tic", "usa", "Chipmunk", UUID.randomUUID()),
new Animal("Tac", "usa", "Chipmunk", UUID.randomUUID())
))
);
Cage amazon = new Cage(
"amazon",
new Position(49.305142d, 1.2154067d),
15,
new LinkedList<>(Arrays.asList(
new Animal("Canine", "amazon", "Piranha", UUID.randomUUID()),
new Animal("Incisive", "amazon", "Piranha", UUID.randomUUID()),
new Animal("Molaire", "amazon", "Piranha", UUID.randomUUID()),
new Animal("De lait", "amazon", "Piranha", UUID.randomUUID())
))
);
this.centers = new Centers();
this.centers.addCenter(new Center(new LinkedList<>(),
new Position(49.30494d, 1.2170602d), "Biotropica"));
this.centers.getCenter()
.stream()
.findFirst()
.get()
.getCages()
.addAll(Arrays.asList(usa, amazon));
}
// -----------------------------------------------------------------------------------------------------------------
// /animals
@ApiOperation(value="Récupère l'ensemble des animaux")
@RequestMapping(path = "/animals", method = GET, produces = APPLICATION_JSON_VALUE)
public Centers getAnimals(){
return this.centers;
}...
因此,正如您所看到的,实际上中心存储在一个变量中(没有持久性!)。我现在想要的是将一些操作外部化(比如/animals 上的每个请求到 AnimalsController...)
但这是我的问题:我想不坚持就去做。我希望我的 Controller 使用相同的统计数据访问/更新相同的变量中心,但我真的不知道我是如何进行的
最佳答案
您可以创建一个 holder 对象,并将其注册到 spring 生命周期:
@Component
public class CentersHolder {
private Centers centers;
// getter + setter
}
然后将该组件 Autowiring 到您想要的每个 Controller 中。 (我建议始终使用构造函数注入(inject),使您的代码更易于测试并且通常更安全)
private final CentersHolder holder;
@Autowired
public YourController(CentersHolder holder) {
this.holder = holder;
}
默认情况下,每个 spring 组件/bean 都是单例,除非您明确告诉它不是一个。因此,您所有的 Controller 将共享同一个实例。
关于java - 从我所有的 Controller 访问一个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55491590/