Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

migrate Spring app from XML to annotations

Tags:

java

spring

I've inherited a Spring 3 app that uses XML files to define and wire together the beans. I know that since Spring 2 these can mostly be replaced with annotations. I would like Spring to:

  • detect beans by scanning certain packages for classes with whatever annotation is used to indicate a Spring bean
  • attempt to autowire-by-name and field in a bean that I have marked with the relevant annotation

What are steps I need to take to make this happen?

like image 385
Dónal Avatar asked Mar 29 '11 16:03

Dónal


2 Answers

The manual has all the info you need: http://static.springsource.org/spring/docs/3.1.0.M1/spring-framework-reference/html/beans.html#beans-annotation-config

The TL;DR version is that you need to add <context:annotation-config/> to your spring config and then annotate your beans with @Component and in your setter of properties annotate with @Autowired

like image 163
CarlosZ Avatar answered Sep 28 '22 14:09

CarlosZ


I shall give you a xml configuration with it anotation based config equivalent respectively, so that you will easily see how to change your bean from xml to java and vice-versa

    `<?xml version="1.0" encoding="UTF-8"?>

        <beans xmlns="http://www.springframework.org/schema/beans"
               xmlns:context="http://www.springframework.org/schema/context"
               xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:p="http://www.springframework.org/schema/p"
               xsi:schemaLocation="
                http://www.springframework.org/schema/beans    
                http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context-4.0.xsd
                http://www.springframework.org/schema/mvc
                http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

            <context:component-scan base-package="com.mycompany.backendhibernatejpa.controller" />
            <mvc:annotation-driven />
            <bean id="iAbonneDao" class="com.mycompany.backendhibernatejpa.daoImpl.AbonneDaoImpl"/> 
            <bean id="iAbonneService" class="com.mycompany.backendhibernatejpa.serviceImpl.AbonneServiceImpl"/>

            <!-- couche de persistance JPA -->
            <bean id="entityManagerFactory"
                  class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
                <property name="dataSource" ref="dataSource" />
                <property name="jpaVendorAdapter">
                    <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">            
                        <property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
                        <property name="generateDdl" value="true" />
                        <property name="showSql" value="true" />
                    </bean>
                </property>
                <property name="loadTimeWeaver">
                    <bean
                        class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
                </property>
            </bean>

            <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">   
                <property name="locations" value="classpath:bd.properties"/>
            </bean>

            <!-- la source de donnéees DBCP -->
            <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" >
                <property name="driverClassName" value="${bd.driver}" />
                <property name="url" value="${bd.url}" />
                <property name="username" value="${bd.username}" />
                <property name="password" value="${bd.password}" />
            </bean>

            <!-- le gestionnaire de transactions -->

            <bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
                <property name="entityManagerFactory" ref="entityManagerFactory" />
            </bean>


            <!-- traduction des exceptions -->
            <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

            <!-- annotations de persistance -->
            <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />


        </beans>` 

this file is named springrest-sevlet. actually you can give the name you want followed by "-servlet" and mention that name in the file web.xml

    ` <web-app> 
             <display-name>Gescable</display-name> 
             <servlet> 
                 <servlet-name>springrest</servlet-name> 
                 <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> 
                 <load-on-startup>1</load-on-startup> 
             </servlet> 
             <servlet-mapping> 
                 <servlet-name>springrest</servlet-name> 
                 <url-pattern>/</url-pattern> 
             </servlet-mapping> 
         </web-app>`

the two files should be place in the folder "WEB-INF". Now the equivalent with anotation based config

    `/*
         * To change this license header, choose License Headers in Project Properties.
         * To change this template file, choose Tools | Templates
         * and open the template in the editor.
         */
        package com.mycompany.backendhibernatejpaannotation.configuration;

        import com.mycompany.backendhibernatejpaannotation.daoImpl.AbonneDaoImpl;
        import com.mycompany.backendhibernatejpaannotation.daoInterface.IAbonneDao;
        import com.mycompany.backendhibernatejpaannotation.serviceImpl.AbonneServiceImpl;
        import com.mycompany.backendhibernatejpaannotation.serviceInterface.IAbonneService;
        import javax.sql.DataSource;
        import org.springframework.context.annotation.Bean;
        import org.springframework.context.annotation.ComponentScan;
        import org.springframework.context.annotation.Configuration;
        import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
        import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver;
        import org.springframework.jdbc.datasource.DriverManagerDataSource;
        import org.springframework.orm.jpa.JpaTransactionManager;
        import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
        import org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor;
        import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
        import org.springframework.web.servlet.config.annotation.EnableWebMvc;

        /**
         *
         * @author vivien saa
         */
        @Configuration
        @EnableWebMvc
        @ComponentScan(basePackages = "com.mycompany.backendhibernatejpaannotation")
        public class RestConfiguration {

            @Bean
            public IAbonneDao iAbonneDao() {
                return new AbonneDaoImpl();
            }

            @Bean
            public IAbonneService iAbonneService() {
                return new AbonneServiceImpl();
            }

        //    @Bean
        //    public PropertyPlaceholderConfigurer placeholderConfigurer() {
        //        PropertyPlaceholderConfigurer placeholderConfigurer = new PropertyPlaceholderConfigurer();
        //        placeholderConfigurer.setLocations("classpath:bd.properties");
        //        return placeholderConfigurer;
        //    }

            @Bean
            public DataSource dataSource() {
                DriverManagerDataSource dataSource = new DriverManagerDataSource();
                dataSource.setDriverClassName("com.mysql.jdbc.Driver");
                dataSource.setUrl("jdbc:mysql://localhost:3306/gescable");
                dataSource.setUsername("root");
                dataSource.setPassword("root");
                return dataSource;
            }

            @Bean
            public HibernateJpaVendorAdapter jpaVendorAdapter() {
                HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
                jpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQL5InnoDBDialect");
                jpaVendorAdapter.setGenerateDdl(true);
                jpaVendorAdapter.setShowSql(true);
                return jpaVendorAdapter;
            }

            @Bean
            public InstrumentationLoadTimeWeaver loadTimeWeaver() {
                InstrumentationLoadTimeWeaver loadTimeWeaver = new InstrumentationLoadTimeWeaver();
                return loadTimeWeaver;
            }

            @Bean
            public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
                LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
                entityManagerFactory.setDataSource(dataSource());
                entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter());
                entityManagerFactory.setLoadTimeWeaver(loadTimeWeaver());
                return entityManagerFactory;
            }

            @Bean
            public JpaTransactionManager jpaTransactionManager() {
                JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
                jpaTransactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
                return jpaTransactionManager;
            }

            @Bean
            public PersistenceExceptionTranslationPostPro`enter code here`cessor persistenceExceptionTranslationPostProcessor() {
                return new PersistenceExceptionTranslationPostProcessor();
            }

            @Bean
            public PersistenceAnnotationBeanPostProcessor persistenceAnnotationBeanPostProcessor() {
                return new PersistenceAnnotationBeanPostProcessor();
            }

        }`

this file must be accompanied by this one

`              
        package com.mycompany.backendhibernatejpaannotation.configuration;

        import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

        /**
         *
         * @author vivien saa
         */
        public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer {

            @Override
            protected Class<?>[] getRootConfigClasses() {
                return new Class[]{RestConfiguration.class};
            }

            @Override
            protected Class<?>[] getServletConfigClasses() {
                return null;
            }

            @Override
            protected String[] getServletMappings() {
                return new String[]{"/"};
            }

        }
        `
like image 44
Vivien SA'A Avatar answered Sep 28 '22 16:09

Vivien SA'A