如果我想从 spring-application-context.xml 中读取 bean 定义,我会在 web.xml 文件中执行此操作。
<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>
如果我想通过 Java 配置类 (AnnotationConfigWebApplicationContext) 读取 bean 定义,我会在 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>
如何在我的应用程序中同时使用两者。就像从配置 xml 文件和带注释的类中读取 bean 一样。
有没有办法在我们使用 AppConfigAnnotatedClass 实例化/使用其余 bean 时在 xml 文件中加载 spring bean。
这没用
xml文件定义bean为
<bean name="mybean" class="org.somepackage.MyBean"/>
Java 类将资源导入为
@ImportResource(value = {"classpath:some-other-context.xml"})
@Configuration
public class MyConfigAnnotatedClass {
@Inject
MyBean mybean;
}
但是 mybean 的值始终为 null,这当然会在调用 mybean 上的方法时给出 nullpointerexception。
最佳答案
您可以注释您的 @Configuration
类
@ImportResource(value = {"classpath:some-other-context.xml"})
@Configuration
public class MyConfigAnnotatedClass {
...
}
让它导入 <beans>
键入 xml 上下文。
你可以反过来做同样的事情。你的@Configuration
类也是一个 @Component
.如果你有 <component-scan>
包含它的包,所有它声明的 beans 都将被添加到上下文中。或者,您可以这样做
<bean name="myAdditionalConfig" class="org.somepackage.MyConfigAnnotatedClass" />
请注意 package
不能用作包结构中的名称。
关于spring-mvc - 如何在 spring mvc 中读取 spring-application-context.xml 和 AnnotationConfigWebApplicationContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19522307/