This example shows how ApplicationContextAware interface can be used to access short-lived scoped bean from a long-lived scoped bean.
ApplicationContextAware
package com.logicbig.example; import java.time.LocalDateTime; public class MyPrototypeBean { private String dateTimeString = LocalDateTime.now().toString(); public String getDateTime() { return dateTimeString; } }
package com.logicbig.example; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class MySingletonBean implements ApplicationContextAware { private ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public void showMessage() { MyPrototypeBean bean = applicationContext.getBean(MyPrototypeBean.class); System.out.println("Hi, the time is " + bean.getDateTime()); } }
package com.logicbig.example; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; @Configuration public class AppConfig { @Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) public MyPrototypeBean prototypeBean() { return new MyPrototypeBean(); } @Bean public MySingletonBean singletonBean() { return new MySingletonBean(); } public static void main(String[] args) throws InterruptedException { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); MySingletonBean bean = context.getBean(MySingletonBean.class); bean.showMessage(); Thread.sleep(1000); bean = context.getBean(MySingletonBean.class); bean.showMessage(); } }
Hi, the time is 2021-05-05T01:40:59.551Hi, the time is 2021-05-05T01:41:00.563
Dependencies and Technologies Used:
Version compatibilities of spring-context with this example:
Versions in green have been tested.