spring-mvc - 如何在 spring mvc 中读取 spring-application-context.xml 和 AnnotationConfigWebApplicationContext

标签 spring-mvc app-config web.xml spring-annotations applicationcontext

如果我想从 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/

相关文章:

wildfly - Wildfly 上 ManagementRealm 中的 webapp

jsp - 未在操作中获取表单数据

spring-boot-starter-web @Autowired 不工作

java - 创建名称为 'sessionFactory' 的 bean 时出错无法实例化默认 tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

spring-mvc - 为什么 Spring-MVC 将 LoadOnStartup 设置为 1?

C# 访问另一个项目的 app.config 时出现问题

c# - 使用 user.config 而不是 app.config

java - 如何在 Intellij IDEA 13.1 中使用 Maven 结构创建 Spring MVC 应用程序?

c# - dll 的 App.config

Spring web.xml 由于 <listener> 无法加载