Rafael Andrade
Rafael Andrade

Reputation: 505

Using @PostContruct in Spring @Component to initialize data

I am using the annotation @PostContruct to initialize some data in @Component using spring.

The problem is the property is initialized only one time. The code inside @Component is something like this.

private int x;

@Inject Repository myRepo;

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

Variable "x" will be initilized on build, and if my data change in my DB, "x will not be updated. Is there a way that I could inject service in a class that do not belong to spring? Without @Component, for example.

MyClass newclass = new MyClass();

So, findAll() will always be called when I initialize the class.

Upvotes: 0

Views: 1797

Answers (1)

Antoniossss
Antoniossss

Reputation: 32507

If you do

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

@Autowired Repository myRepo;

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

Instances of bean scoped as prototype are created everytime they are requested by eithed CDI context or when directly requested from factory.

Alternatively you can do

@Component()
public class MyClass(){

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

In both cases you will have to use Spring's CDI to get new instance of MyClass.

Upvotes: 4

Related Questions