开发者

Using Spring in a portlet without Spring MVC

开发者 https://www.devze.com 2023-01-10 00:51 出处:网络
Is there a way to develop portlets with spring without using the DispatcherPortlet? I want to use other technologies for the UI, mainly Vaadi开发者_如何转开发n. Spring is used for DI and other stuff.

Is there a way to develop portlets with spring without using the DispatcherPortlet? I want to use other technologies for the UI, mainly Vaadi开发者_如何转开发n. Spring is used for DI and other stuff. Is there something similar to ContextLoaderListener class in the Portlet side?


Looking at the Spring documentation: You can create an ApplicationContext as follows:

ApplicationContext context =
    new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});

Referencing xml files on your classpath.

You can then get beans by calling context.getBean("beanName"). No need for Spring MVC.


I was hoping for a more detailed answer than what Noel gave. Maybe there is some best practice to this? Here is my current solution:

Give the xml file locations as a init parameter to my portlet. My init method looks something like this

@Override
public void init(PortletConfig config) throws PortletException {
    super.init(config);
    String configLocations = config.getInitParameter("contextConfigLocation");
    ClassPathXmlApplicationContext springContext = new ClassPathXmlApplicationContext();
    springContext.setConfigLocation(configLocations);
    springContext.refresh();
    config.getPortletContext().setAttribute(APPLICATION_CONTEXT_ATTRIBUTE, springContext);
}

Now I can access my applicationContext through PortletContext every time I need.

(ApplicationContext) portalContext.getAttribute(APPLICATION_CONTEXT_ATTRIBUTE);

APPLICATION_CONTEXT_ATTRIBUTE is just string constant that I made up. I'm still open for better solutions.


You can use PortletApplicationContextUtils to retrieve the web application context:

ApplicationContext ctx = PortletApplicationContextUtils.getWebApplicationContext(getPortletContext());

Then you just need to add some configuration on your web.xml.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号