【问题标题】:Is it possible to create some beans using xml and the remaining beans using annotation based approach in the same java web application是否可以在同一个 Java Web 应用程序中使用 xml 创建一些 bean,并使用基于注释的方法创建剩余的 bean
【发布时间】:2015-09-29 10:53:30
【问题描述】:

我有一个 Web 项目,其中使用 Spring Java 注释注入了 bean。现在在同一个 Web 项目中,我想使用基于 xml 的配置创建几个 bean。 (我很难在这里给出详细的解释,我为什么要这样做)。所以为了实现这一点,我在web.xml 中指定了ContextLoaderListener 和contextConfigLocation。这样做之后,当我在服务器上部署我的项目战争时,我发现只有那些使用 xml (applicationContext.xml) 创建的 bean 被创建,Spring 无法创建和注入使用基于注释的方法创建的 bean。

这种类型的用例是否可以实现,即使用注解创建一些 bean 和使用 applicationContext.xml 为同一个项目创建一些。如果是,我将不胜感激。

谢谢。

【问题讨论】:

  • 你可以组合任何你想要的东西,但是你必须告诉spring你想要使用这些bean并使用基于注释的配置。所以基本上确保这些 bean 被context:component-scan检测到

标签: java spring spring-mvc jakarta-ee


【解决方案1】:

尝试类似:

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.Bean;


@Configuration
@ImportResource("spring-xml-configuration-file.xml")
public class ConfigClass { 

    ...

     @Bean
     public Object bean1() {
        ...
    }
}

@Configuration 指定您的 java 类是 Spring 的配置。 并且@TmportResource 允许这些类使用在xml 配置文件中定义的bean。

【讨论】:

    【解决方案2】:

    是的,可能。

    您需要在applicationContext.xml 中添加以下<context:component-scan /> 标记以识别带注释的spring bean 并使其实例化。

    • applicationContext.xml

      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
             xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                                 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
      
           <!-- Annotated beans base package location to get it instantiated 
                at the time of spring context startup -->
           <context:component-scan base-package="com.example.service.beans"/>
      
          <!-- normal bean configured in xml -->
          <bean id="userDao" class="com.example.dao.UserDao" />
      
      </beans>
      

      上述基本包下的所有带注释的 bean 都将与您在 xml 文件中配置的普通 bean(&lt;beans/&gt;) 一起实例化。不要忘记将spring-context-&lt;version&gt;.xsd 添加到您的applicationContext.xml。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-05
      • 1970-01-01
      • 2019-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多