user697911
user697911

Reputation: 10551

Does it construct twice if I autowire in two places?

In Spring, I have a @Service bean to initialize it:

@PostConstruct
private void init() throws Exception {
    ...
}

If then I use @Autowired to use the bean above in two different classes, will the 'init' be executed twice or only once? I hope it only executes once, because my initialization of the bean is heavy.

Also, is it always good to use @PostConstruct to initialize a bean? So far I have been always doing this.

Upvotes: 0

Views: 193

Answers (1)

Hemeroc
Hemeroc

Reputation: 2244

That depends if your bean is scoped prototype or singleton.

See bean scopes

You should consider using constructors instead wherever possible. To keep everything easier testable and reduce complexity.

Upvotes: 1

Related Questions