Embedding ApplicationContext in Wicket component with @SpringBean fails

I have a Spring project with Wicket. I can successfully add Services in Wicket components using the @SpringBean annotation.

Now I want to access the context of the Spring application. So I declared a member variable of type ApplicationContext and annotated it using @SpringBean, like other services:

trying to use @SpringBean to enter application

public class MyPanel extends Panel { @SpringBean private ApplicationContext applicationContext; ... } 

However, at runtime this gives an error

 bean of type [org.springframework.context.ApplicationContext] not found 

Is it not possible to implement ApplicationContext in Wicket Components? If so, what would be the appropriate way to access the ApplicationContext?

+4
source share
2 answers

ApplicationContext must be available in your application class.

 ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext); 

Create the getApplicationContext method in your application class.

 public class MyApplication extends WebApplication { public ApplicationContext getAppCtx() { return WebApplicationContextUtils.getWebApplicationContext(servletContext); } } 

Access to the application object can be obtained from any calibration component.

 public class MyPanel extends Panel { public MyPanel(String id) { ... ApplicationContext appCtx = ((MyApplication) getApplication()).getAppCtx(); ... } } 
+5
source

ApplicationContext cannot be entered as a bean, as this does not mean a bean.

Spring provides the ApplicationContextAware interface to provide your application with an easy way to get to the spring context:

 public class MyContentProvider extends Panel implements ApplicationContextAware { private ApplicationContext applicationContext; public void setApplicationContext(ApplicationContext ctx) { applicationContext=ctx; } public ApplicationContext getApplicationContext() { return applicationContext; } } 

The spring mechanism, creating an instance of the bean, will detect the interface and access the device.

Enter this supplier in your calibration component:

 public class MyPanel extends Panel { @SpringBean private MyContentProvider contextProvider; ... } 

And use it:

 contextProvider.getApplicationContext().getBean("foo"); 
+4
source

Source: https://habr.com/ru/post/1402892/


All Articles