aos
aos

Reputation: 197

Accessing beans in portlet specific context programmatically

I have a portlet application. It is configured using Spring framework IoC container. I am using org.springframework.web.context.ContextLoaderListener to load my context.

I have an application context at root level (applicationContext.xml) and a portlet specific context (MyPortlet-portlet.xml).

I have a portlet of type org.springframework.web.portlet.DispatcherPortlet which is wired up to a Controller. In the Controller I want to access one of the beans (e.g. bean with id "myBean") I have defined in my portlet specific context. I have tried

MyBean mybean = (MyBean)PortletApplicationContextUtils.getWebApplicationContext(
    getPortletContext()).getBean("myBean")

However only the beans in my application context are available here - none of my beans in my portlet specific context are available.

Is there a way to access the beans in my portlet specific context?

Thanks

Upvotes: 1

Views: 1764

Answers (1)

skaffman
skaffman

Reputation: 403451

Firstly, can't you just wire in the bean to your controller in the normal way, rather than retrieving it programmatically?

Failing that, you should realise that getWebApplicationContext() gets a reference to the root webapp context, not the servlet app context:

Find the root WebApplicationContext for this portlet application, which is typically loaded via ContextLoaderListener or ContextLoaderServlet.

If your controller needs a handle on its own context, then it should implement ApplicationContextAware or BeanFactoryAware, or it can use @Autowired ApplicationContext if you want to use autowiring.

Upvotes: 1

Related Questions