Page tree
Skip to end of metadata
Go to start of metadata

Spring beans and Magnolia components are managed separately by their respective dependency injection contexts.

Therefore its not possible to just inject a Spring bean in a Magnolia component or vice versa. The sections below shows how both directions can be achieved.

Accessing a Spring bean from a Magnolia component or Magnolia instantiated object

For objects managed by Magnolia, those declared in your module descriptor, an action in an app, or a RenderingModel object, you need to query the Spring ApplicationContext to access a Spring bean.

The first step is finding the ApplicationContext to query. This is done by looking it up in the ServletContext using WebApplicationContextUtils, Magnolia will happily inject the ServletContext when it creates your object. We then query it to get access to the bean.

WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
MyBean bean = wac.getBean(MyBean.class);

The ApplicationContext can also be asked to perform autowiring on any object. You can use this to have Spring inject dependencies in your component. They need to be annotated with @Autowired and you need to have <context:annotation-config/> specified in your applicationContext.xml for this to work.

public class MyComponent {

    private MyBean myBean;

    public MyComponent(ServletContext servletContext) {
        WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);

For RenderingModels Blossom provides an abstract base class that performs auto wiring on the object itself. See the Blossom documentation on autowiring RenderingModel classes for more details.

Accessing a Magnolia component from a Spring bean

Magnolia components can be queried for by calling the static method Components.getComponent().

MyComponent myComponent = Components.getComponent(MyComponent.class);

Blossom also provides a way to expose Magnolia components in the Spring ApplicationContext so they can be injected and accessed just as if they were managed by Spring. See the Blossom documentation on dependencies on Magnolia components for more details.