Question

I would like to have a (singleton) bean initialized only after it is actually used (instead of when it is only autowired). Let say I have a Client that I want to initialize only when I want to call any of its methods

@Component
@Lazy(true)
public class Client {

    @PostConstruct
    void init() {}
    void action(){}
}

And I have a Service class that sometimes use it (and maybe sometimes not).

@Service
public class Service {

    @Autowired
    Client client;

    void action1WithClient(){}
    void action2WithClient(){}
    void actionWithoutClient(){}
}

As it is now, the client is initialized right on the application startup without actually being used due to @Autowired and the fact that Service is eagerly loaded.

Currently only solution that comes to my mind is to do kind of double-checked locking with explicitly asking for Client bean from spring application context when someone tries to use (ie. without @Autowired) or (maybe even better) to do "manual" lazy loading inside the Client.

Question: Is there a "spring" way to postpone the initialization of client until any of its method is actually called (e.g. something like lazy loading is working for hibernate collections)?

I am using Spring 4.

Was it helpful?

Solution 2

Edit:
The easiest way is @ComponentScan(lazyInit = true, basePackages=...).

Previous answer:
There is http://docs.spring.io/spring/docs/3.0.x/javadoc-api/org/springframework/aop/target/LazyInitTargetSource.html A bean wrapped with LazyInitTargetSource will not be created until the first actual usage. How to nicely wrap most of your beans with this wrapper? One possible way is to create your own BeanFactoryPostProcessor...

OTHER TIPS

Ah, ok, I should read the javadoc more properly... Solution seems to add anotation "each" autowired dependeny:

@Autowired
@Lazy
Client client;

Anyway - if anybody knows if it is possible to omit such declarations, since it might be error prone - one can easily forget to use @Lazy at each injection point.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top