This example shows how to use Java 8 functions to solve shorter-lived bean injection problem.
We are going to inject java.util.function.Function into a singleton bean. Whenever Function#apply() method is called, it will return a new instance of a prototype bean.
Example
Prototype bean
package com.logicbig.example;
public class MyPrototypeBean {
private String message;
public MyPrototypeBean(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
Singleton bean
package com.logicbig.example;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.function.Function;
public class MySingletonBean {
@Autowired
private Function<String, MyPrototypeBean> myPrototypeBeanFunction;
public void showMessage() {
MyPrototypeBean bean = myPrototypeBeanFunction.apply("Hi there!");
System.out.printf("message: %s - instance: %s%n", bean.getMessage(), System.identityHashCode(bean));
}
}
Defining beans and running main method
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;
import java.util.function.Function;
@Configuration
public class AppConfig {
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public MyPrototypeBean prototypeBean(String name) {
return new MyPrototypeBean(name);
}
@Bean
public Function<String, MyPrototypeBean> prototypeBeanFunction() {
return name -> prototypeBean(name);
}
@Bean
public MySingletonBean singletonBean() {
return new MySingletonBean();
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
MySingletonBean bean = context.getBean(MySingletonBean.class);
bean.showMessage();
// one more time
bean = context.getBean(MySingletonBean.class);
bean.showMessage();
}
}
Outputmessage: Hi there! - instance: 1071410267 message: Hi there! - instance: 1563125357
Example ProjectDependencies and Technologies Used: - spring-context 6.1.2 (Spring Context)
Version Compatibility: 4.1.3.RELEASE - 6.1.2 Version compatibilities of spring-context with this example: Versions in green have been tested.
- JDK 17
- Maven 3.8.1
|