Announcement Announcement Module
Collapse
No announcement yet.
Expose Beans from Child Context To Parent Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Expose Beans from Child Context To Parent

    Hi, I have an application context structure that looks like this:

    -- web-context (xml, loaded by web container)
    ---- users-context (javaconfig, defines all the beans necessary for creating UserService)
    ---- products-context (javaconfig, defines all the beans necessary for creating ProductService)

    The reason for this is so that the parent context is not polluted by all the additional beans created by the two child contexts.

    To create these child contexts, we use a custom class, ChildContextFactoryBean, which creates an application context and sets web-context as its parent. The following is defined in web-context:

    Code:
    <!-- Type of bean created by factory is ApplicationContext -->
    <bean id="usersContext" class="com.example.ChildContextFactoryBean">
        <property name="contextClass" value="com.example.users.UsersContext" />
    </bean>
    
    <!-- Type of bean created by factory is ApplicationContext -->
    <bean id="productsContext" class="com.example.ChildContextFactoryBean">
        <property name="contextClass" value="com.example.products.ProductsContext" />
    </bean>
    
    <!-- Exposes user service to the parent context -->
    <bean id="userService" factory-bean="usersContext" factory-method="getBean">
        <constructor-arg type="java.lang.String" value="userService" />
        <constructor-arg type="java.lang.Class" value="com.example.users.UserService" />
    </bean>
    This configuration was working fine until I added an EntityManager to userService (using @PersistenceContext). The problem is that when it is re-defined in the parent context which doesn't have a EntityManagerFactory, it is failing. How can I expose userService in the parent context for autowiring without subjecting it to the bean lifecycle in the parent context?

    Thanks,
    Andy

  • #2
    OK, I fixed my problem by adding additional functionality to the ChildContextFactoryBean. The ChildContextFactoryBean now registers the needed beans to the parent context using BeanFactory's registerSingleton() method:

    Code:
    <bean id="usersContext" class="com.example.ChildContextFactoryBean">
        <property name="contextClass" value="com.example.users.UsersContext" />
        <property name="exposedSingletonBeanNames">
            <set>
                <value>userService</value>
                <value>anotherBeanToExpose</value>
            </set>
        </property>
    </bean>
    If anyone is interested in the code for the ChildContextFactoryBean let me know, though it only supports annotation configured application contexts right now (no XML support).

    Thanks,
    Andy

    Comment

    Working...
    X