繁体   English   中英

是否可以在同一个Java Web应用程序中使用xml创建一些bean,并使用基于注释的方法创建其余bean?

[英]Is it possible to create some beans using xml and the remaining beans using annotation based approach in the same java web application

我有一个Web项目,其中使用Spring Java注释注入了bean。 现在在同一个Web项目中,我想使用基于xml的配置来创建几个bean。 (我很难在这里提供详细说明,为什么要这样做)。 为此,我在web.xml指定了ContextLoaderListenercontextConfigLocation 完成此操作后,当我在服务器上部署项目战时,我发现仅创建了使用xml( applicationContext.xml )创建的那些bean,Spring无法创建和注入使用基于注释的方法创建的bean。

是否可以实现这种用例类型,即为同一项目使用批注创建一些Bean,并使用applicationContext.xml创建某些用例? 如果是的话,我将不胜感激。

谢谢。

尝试类似的东西:

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。

是的,可能。

您需要在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( <beans/> )一起实例化。 不要忘记将spring-context-<version>.xsdapplicationContext.xml

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM