简体   繁体   中英

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

I have a web project in which I have beans injected using spring java annotations. Now in the same web project, I want to create few beans using xml based configuration. (It will be hard for me to give here detail explanation, Why I want to do so). So to achieve this, I specified a ContextLoaderListener and contextConfigLocation in my web.xml . After doing this, When I deployed my project war on server, I found that only those beans created using xml ( applicationContext.xml ) were getting created, Spring was not able to create and inject the beans created using annotations based approach.

Is this type of use case possible to achieve ie creating some beans using annotations and some using applicationContext.xml for the same project. If yes, I would appreciate the help on the same.

Thanks.

Try something like :

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 specified that your java class is a Configuration for Spring. And @TmportResource allow these class to use beans defined in xml configuration files.

Yes, Possible.

You need to add the below <context:component-scan /> tag in applicationContext.xml to recognize annotated spring beans and to get it instantiated.

  • 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> 

    All the Annotated beans present under the above mentioned base-package will be instantiated along with the normal beans( <beans/> ) which you configured in xml file. Don't forget to add spring-context-<version>.xsd to your applicationContext.xml .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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