Spring @Component中使用@PostContruct初始化数据

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

我正在使用注释@PostContruct使用spring初始化@Component中的一些数据。

问题是该属性仅初始化一次。 @Component里面的代码是这样的。

private int x;

@Inject Repository myRepo;

@PostConstruct
private void init () {
    this.x = myRepo.findAll().size();
}

变量“x”将在构建时初始化,如果我的数据库中的数据发生更改,“x”将不会更新。有没有一种方法可以在不属于 spring 的类中注入服务?没有@Component,例如。

MyClass newclass = new MyClass();

因此,当我初始化类时,

findAll()
将始终被调用。

java spring spring-boot spring-data-jpa
1个回答
4
投票

如果你这样做

@Component
@Scope('prototype') // thats the trick here
public class MyClass(){

@Autowired Repository myRepo;

@PostConstruct
private void init () {
    this.x = myRepo.findAll().size();
}
}

每次 CDI 上下文请求或直接从工厂请求时,都会创建范围为

prototype
的 bean 实例。

你也可以这样做

@Component()
public class MyClass(){

    public MyClass(@Autowired Repository myRepo){
      this.x = myRepo.findAll().size();
    }
}

在这两种情况下,您都必须使用 Spring 的 CDI 来获取 MyClass 的新实例。

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