【问题标题】:migrate Spring app from XML to annotations将 Spring 应用程序从 XML 迁移到注释
【发布时间】:2011-07-25 11:17:25
【问题描述】:

我继承了一个 Spring 3 应用程序,该应用程序使用 XML 文件来定义和连接 bean。我知道从 Spring 2 开始,这些大部分都可以用注释替换。我希望 Spring 能够:

  • 通过扫描某些包中的类来检测 bean,其中包含用于指示 Spring bean 的任何注释
  • 尝试在我用相关注释标记的 bean 中按名称和字段自动装配

我需要采取哪些步骤来实现这一目标?

【问题讨论】:

    标签: java spring


    【解决方案1】:

    我会给你一个xml配置,它分别对应基于注解的配置,这样你就可以很容易地看到如何将你的bean从xml更改为java,反之亦然

        `<?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>` 
    

    这个文件被命名为 springrest-sevlet。其实你可以给名字 您希望后跟“-servlet”并在文件中提及该名称 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>`
    

    这两个文件应该放在文件夹“WEB-INF”中。 现在等效于基于注释的配置

        `/*
             * 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();
                }
    
            }`
    

    这个文件必须有这个文件

    `              
            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[]{"/"};
                }
    
            }
            `
    

    【讨论】:

      【解决方案2】:

      手册包含您需要的所有信息:http://static.springsource.org/spring/docs/3.1.0.M1/spring-framework-reference/html/beans.html#beans-annotation-config

      TL;DR 版本是您需要将 &lt;context:annotation-config/&gt; 添加到您的 spring 配置中,然后使用 @Component 注释您的 bean,并在您的属性设置器中使用 @Autowired 注释

      【讨论】:

      • 只是补充 CarlosZ 的回答。如果您正在创建一个新组件并且想要自动装配一些 bean,您不必创建 getter 和 setter,只需将 @Autowired 注释添加到属性声明中,您就可以开始了。
      • 正确@Lucas,您可以进行setter注入、属性注入(不需要setter)或构造函数注入(我个人最喜欢的,因为我认为在调用构造函数时应该完全初始化对象,包括依赖项)。
      【解决方案3】:

      我认为首先要做的就是慢慢来。一次只选择一项服务并迁移它,因为您有理由接触它。使用大量的 spring 配置是一种肯定的方式,在生产中你只需要偶尔需要一次依赖。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-22
        • 1970-01-01
        • 1970-01-01
        • 2012-04-08
        • 1970-01-01
        • 2015-11-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多