In my Spring Boot based application I’ve a @Component class that has code similar to this:
ExecutorService executorService = Executors.newFixedThreadPool(poolSize);
// Start a separate thread for each entry
Map<Long, Future<Integer>> calls = new HashMap<>();
for (MyClass info : list) {
Callable<Integer> callable = new TableProcessor(info);
Future<Integer> future = executorService.submit(callable);
calls.put(info.getId(), future);
}
The AutoWiring is not working in the TableProcessor class because (I think) I am creating an instance using ‘new’. What’s the best way to ‘create a new instance for each entry in my list’?
Note: Adding a ‘Bean’ to Application class won’t work in this case because I want a new instance for each thread.
Go to the src > main > java > your package name > right-click > New > Java Class and create your component class and mark it with @Component annotation.
If you autowire the bean in multiple places, Spring will still provide you with the same instance. When you autowire a prototype bean, Spring will initialize a new instance of the bean. If you autowire the bean in multiple places, then Spring will create a new instance for every place you autowire the bean.
@Component is an annotation that allows Spring to automatically detect our custom beans. In other words, without having to write any explicit code, Spring will: Scan our application for classes annotated with @Component. Instantiate them and inject any specified dependencies into them.
I had a similar problem and I solved it using the ApplicationContext.
Here's an example because I like to look at code rather than explain things, so maybe it will help someone in the same boat:
First, here's the Spring component that I want to create a new instance of:
@Component
@Scope("prototype")
public class PopupWindow extends Window{
private String someVar;
@PostConstruct
public void init(){
//stuff
someVar="hi";
}
}
Here's the class where I want 2 instances of this Spring component:
@Component
@Scope("session")
public class MainWindow extends Window{
private PopupWindow popupWindow1;
private PopupWindow popupWindow2;
@Autowired
private ApplicationContext applicationContext;
@PostConstruct
public void init(){
popupWindow1 = applicationContext.getBean(PopupWindow.class);
popupWindow2 = applicationContext.getBean(PopupWindow.class);
}
}
In my particular case, I'm using Vaadin + Spring, and these annotations use the Vaadin versions i.e. @SpringComponent and @UIScope instead of @Scope("session"). But the @Scope("prototype") is the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With