Lifecycleโ
Clawject allows us to attach custom actions to bean or application creation and destruction,
and it is done using the @PostConstruct and @PreDestroy decorators.
@PostConstruct and @PreDestroy can be used in @Configuration, @ClawjectApplication classes and in Beans.
You can decorate method or property with arrow function, also decoration target should not be static.
@PostConstruct and @PreDestroy can be used together at the same method โ so the method will be called twice.
Note that @PostConstruct and @PreDestroy works a little different in configuration classes and in Beans,
when using in configuration classes - you can pass arguments to the method,
these arguments will be treated as a dependencies, and container will inject appropriate Beans to the method, in other hand,
when using in Bean - you can't pass arguments to the method,
container will not inject anything to the method and will report compilation error.
@PostConstructโ
Clawject calls the methods annotated with @PostConstruct only once, just after the initialization of bean or application.
@PostConstruct in Contextโ
Let's use the @PostConstruct decorator in the @Configuration class:
@ClawjectApplication
class Application {
@Bean foo = 'string';
@PostConstruct
postConstruct(stringBean: string) { // <- "foo" bean will be injected here
console.log(`MyContext has been created, "stringBean" value is ${stringBean}`);
}
}
@PostConstruct in Beanโ
Let's use the @PostConstruct decorator in the Bean:
class Foo {
@PostConstruct
postConstruct() {
console.log('Foo bean has been created');
}
}
Now when we register this class as a Bean in context -
the postConstruct method will be called when Foo instance is created.
@PreDestroyโ
Clawject calls the methods annotated with @PostConstruct only once, just before context clearing or bean removal from context.
The purpose of this method should be to release resources or perform other cleanup tasks, such as closing a database connection, before the bean gets destroyed.
@PreDestroy in Contextโ
Let's use the @PreDestroy decorator in the Context:
@ClawjectApplication
class Application {
@Bean foo = 'string';
@PreDestroy
preDestroy(stringBean: string) { // <- "foo" bean will be injected here
console.log(`MyContext is going to be destroyed, "stringBean" value is ${stringBean}`);
}
}
@PreDestroy in Beanโ
Let's use the @PreDestroy decorator in the Bean:
class Foo {
@PreDestroy
preDestroy() {
console.log('Foo bean is going to be destroyed');
}
}
Now when we register this class as a Bean in context -
the preDestroy method will be called when Foo bean is going to be destroyed.