Spring:将项目配置转换为非XML

时间:2015-07-06 01:42:49

标签: java xml spring maven spring-mvc

我已经使用xml文件设置了一个应用程序,它可以正常工作,但我需要将配置转换为非xml。 它一直工作到某个阶段,直到我开始添加@Autowired注释,所以我不确定我的哪些设置给我带来了麻烦。

我决定从头开始设置,但我需要一些帮助。这是我的XML代码:

的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee" 
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
         version="3.0">
  <display-name>test</display-name>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
            classpath:application-context.xml
            classpath:persistence-context.xml
        </param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/api/*</url-pattern>
  </servlet-mapping>
</web-app>

调度-servlet.xml中

<?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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd 
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <context:component-scan base-package="ve.com.pt" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="ve.com.pt.induccion.HibernateAwareObjectMapper" />
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <bean id="documentationController" class="org.jsondoc.springmvc.controller.JSONDocController">
        <constructor-arg name="version" value="1.0"/>
        <constructor-arg name="basePath" value="http://localhost:4848/induccion/api"/>
        <constructor-arg name="packages">
        <list>
        <value>ve.com.pt.induccion</value>
        </list>
        </constructor-arg>
    </bean>
</beans>

应用context.xml中

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
        xmlns:context="http://www.springframework.org/schema/context" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="ve.com.pt.induccion" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository" />
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Service" />
    </context:component-scan>

</beans>

持久性context.xml中

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
        xmlns:tx="http://www.springframework.org/schema/tx" 
        xmlns:jpa="http://www.springframework.org/schema/data/jpa" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd 
            http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/spring_prueba" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>

    <bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
        <property name="defaultDataSource" ref="dataSource" />
    </bean>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitManager" ref="persistenceUnitManager" />
        <property name="persistenceUnitName" value="persistenceUnit" />
    </bean>

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

    <tx:annotation-driven transaction-manager="transactionManager" />

    <jpa:repositories base-package="ve.com.pt.induccion" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager" />
</beans>

因此XML配置工作,但它需要基于java,并摆脱.xml文件。 以下代码是我尝试将其转换为java代码。

AppInitializer.java

package ve.com.test.init;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class AppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        WebApplicationContext context = getContext();
        servletContext.addListener(new ContextLoaderListener(context));
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
    }

    private AnnotationConfigWebApplicationContext getContext() {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.setConfigLocation("ve.com.test.config");
        return context;
    }

}

WebMvcConfig.java

package ve.com.test.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@EnableWebMvc
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
}

AppConfig.java

package ve.com.test.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@ComponentScan(basePackages = "ve.com.test", 
                includeFilters = @ComponentScan.Filter(value = {Controller.class, Service.class, Repository.class}, type = FilterType.ANNOTATION))
@EnableTransactionManagement
public class AppConfig {

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

    @Bean
    public DefaultPersistenceUnitManager persistenceUnitManager(){
        DefaultPersistenceUnitManager dpum = new DefaultPersistenceUnitManager();
        dpum.setDefaultDataSource(dataSource());
        return dpum;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(){
        LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean();
        emfb.setPersistenceUnitManager(persistenceUnitManager());
        return emfb;
    }

    @Bean
    public PlatformTransactionManager transactionManager(){
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(
                entityManagerFactoryBean().getObject() );
        return transactionManager;
    }

    @Bean
    public MappingJackson2HttpMessageConverter jacksonMapper(){
        MappingJackson2HttpMessageConverter jm = new MappingJackson2HttpMessageConverter();
        jm.setObjectMapper(new HibernateAwareObjectMapper());
        return jm;
    }

}

HibernateAwareObjectMapper.java

package ve.com.test.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module;

public class HibernateAwareObjectMapper extends ObjectMapper {
    private static final long serialVersionUID = 1L;

    public HibernateAwareObjectMapper() {
        registerModule(new Hibernate4Module());
    }
}

所以,这个基于java的代码正在工作,而我只有一些随机的Controller返回了一个&#34; hello world&#34;。然而,当我开始添加一些控制器,服务,存储库和jpa实体并自动装配需要@Autowired时,我开始遇到这个恼人的错误:

  

SEVERE:将上下文初始化事件发送给侦听器的异常   类的实例   org.springframework.web.context.ContextLoaderListener   org.springframework.beans.factory.BeanCreationException

它一直在继续,基本上说它不能为我的控制器,服务和存储库创建bean。 我的xml配置的工作方式,我从来不需要创建bean,因为它们是自动生成的,而且是我需要在java代码中复制的东西之一。

我真的很感激任何帮助。

0 个答案:

没有答案