3

In case I want to read bean definitions from spring-application-context.xml, I would do this in web.xml file.

<context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/applicationContext.xml </param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> 

In case I want to read bean definitions through Java Configuration Class (AnnotationConfigWebApplicationContext), I would do this in web.xml

<servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextClass</param-name> <param-value> org.springframework.web.context.support.AnnotationConfigWebApplicationContext </param-value> </init-param> <init-param> <param-name>contextConfigLocation</param-name> <param-value> org.package.MyConfigAnnotatedClass </param-value> </init-param> </servlet> 

How do I use both in my application. like reading beans from both configuration xml file and annotated class.

Is there a way to load spring beans in xml file while we are using AppConfigAnnotatedClass to instantiate/use rest of the beans.

This didnt work

Xml file defines bean as

<bean name="mybean" class="org.somepackage.MyBean"/> 

Java Class Imports Resources as

@ImportResource(value = {"classpath:some-other-context.xml"}) @Configuration public class MyConfigAnnotatedClass { @Inject MyBean mybean; } 

But mybean value is always null which ofcourse will give nullpointerexception when calling method on mybean.

1 Answer 1

4

You can annotate your @Configuration class with

@ImportResource(value = {"classpath:some-other-context.xml"}) @Configuration public class MyConfigAnnotatedClass { ... } 

to have it import <beans> type xml contexts.

You can do the same thing the other way around. Your @Configuration class is also a @Component. If you have a <component-scan> that includes its package, all its declared beans will be added to the context. Alternatively, you can do

<bean name="myAdditionalConfig" class="org.somepackage.MyConfigAnnotatedClass" /> 

Note that package cannot be used as a name in the package structure.

Sign up to request clarification or add additional context in comments.

3 Comments

@Suvasis XML might not show properly in comments. Please edit your question and add it as code there.
I have edited my question showing what I have tried but did not work. Could you tell me how did you import the bean in @Configuration class. or where did you place your xml file.
@Suvasis If MyConfigAnnotatedClass is the class you've specified in the contextConfigLocation param, then what you have should work. This xml file should be a separate from the one loaded by the ContextLoaderListener.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.