如果我想从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。
有没有办法在 xml 文件中加载弹簧豆,而我们使用 AppConfigAnnotatedClass 来实例化/使用其余的豆子。
这不起作用
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>
,则其所有声明的 Bean 都将添加到上下文中。或者,您可以做
<bean name="myAdditionalConfig" class="org.somepackage.MyConfigAnnotatedClass" />
请注意,package
不能用作包结构中的名称。