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

时间:2018-07-23 13:53:18

标签: java spring spring-boot spring-data-jpa

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

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

private int x;

@Inject Repository myRepo;

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

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

MyClass newclass = new MyClass();

因此,在初始化类时始终会调用findAll()。

1 个答案:

答案 0 :(得分: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的新实例。