The java class which represented as Spring Bean is called as Bean Class.
-> The java class which is managed by IOC is called as Spring Bean.
-> Spring Beans life cycle will be managed by IOC.
-> For Spring Beans Obj creation and Obj destruction will be taken by IOC container.
-> We can execute life cycle methods for Spring Bean.
-> In Spring Boot, we can work with Bean Lifecycle methods in 2 ways
1) By Implementing interfaces ( IntializingBean & DisposableBean )
2) By Using Annotations ( @PostConstruct & @PreDestory )
// Interface Approach
@Component
public class Motor implements InitializingBean, DisposableBean {
public Motor() {
System.out.println("Motor :: Constructor");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("afterPropertiesSet() method called....");
}
@Override
public void destroy() throws Exception {
System.out.println("destroy() method called....");
}
}
// Annotation Approach
@Component
public class Engine {
public Engine() {
System.out.println("Engine :: Constructor");
}
@PostConstruct
public void init() {
System.out.println("start engine....");
}
@PreDestroy
public void destroy() {
System.out.println("stop engine...");
}
}
Comments
Post a Comment