In out last example, instead of using ScopedProxyMode.TARGET_CLASS , we can specify proxyMode as ScopedProxyMode.INTERFACES with @Scope annotation.
This mode needs to be specified if we are autowiring interface rather than a concrete class.
Spring injects JDK interface based proxy rather than CGLIB class based proxy.
This example is a modification of our previous example. We are going to create an interface for our prototype bean so that it can be injected into wider scoped singleton bean using JDK interface based proxy mode.
Example
Interface for prototype bean
package com.logicbig.example;
public interface IPrototype {
String getDateTime();
}
Prototype bean
package com.logicbig.example;
import java.time.LocalDateTime;
public class MyPrototypeBean implements IPrototype {
private String dateTimeString = LocalDateTime.now().toString();
@Override
public String getDateTime() {
return dateTimeString;
}
}
Singleton bean
package com.logicbig.example;
import org.springframework.beans.factory.annotation.Autowired;
public class MySingletonBean {
@Autowired
private IPrototype prototypeBean;
public void showMessage(){
System.out.println("Hi, the time is "+prototypeBean.getDateTime());
}
}
Main class
package com.logicbig.example;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.*;
@Configuration
public class AppConfig {
@Bean
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE,
proxyMode = ScopedProxyMode.INTERFACES)
public IPrototype 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.showMessage();
}
}
OutputHi, the time is 2021-05-05T02:09:20.612 Hi, the time is 2021-05-05T02:09:21.634
Example ProjectDependencies and Technologies Used: - spring-context 6.1.2 (Spring Context)
Version Compatibility: 3.2.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
|