spring mvc javaConfig版本搭建常见问题

本文详细记录了在使用Spring MVC Java Config版框架搭建过程中遇到的问题及解决方案,包括MediaType配置、ComponentScan注解、fastjson版本兼容、事务管理器配置等。旨在帮助程序员解决实际开发中可能遇到的类似问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天在spring mvc javaConfig版本框架搭建上耗了一天,终于给搭建出来了,下面是搭建过程中遇到的一些问题,记录下来方便以后复习,也为程序员兄弟们提供参考:


javaConfig spring mvc核心配置文件中对资源文件处理的适配置配置中MediaType的实例化问题:用一个字符串参数来创建org.springframework.http.MediaType实例的时候,用MediaType.valueOf(String)方法,不能用new MediaType(String)不然会报错;(Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter]: Factory method 'annotationMethodHandlerAdapter' threw exception; nested exception is java.lang.IllegalArgumentException: Invalid token character '/' in token "text/html"

package com.springmvc.config;

import com.springmvc.util.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by baich on 2016/1/26.
 */
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.springmvc.controller"})
public class SpringServlet extends WebMvcConfigurerAdapter {

    /**
     * 服务器内部资源解析器
     * @return
     */
    @Bean
    public InternalResourceViewResolver internalResourceViewResolver() {

        InternalResourceViewResolver irvr = new InternalResourceViewResolver();

        irvr.setPrefix("/");

        irvr.setSuffix(".jsp");

        return irvr;
    }

    /**
     * mediaType supportMediaTypes converter converters
     * 媒体适配器配置
     * @return
     */
    @Bean
    public AnnotationMethodHandlerAdapter annotationMethodHandlerAdapter() {
        AnnotationMethodHandlerAdapter amha = new AnnotationMethodHandlerAdapter();

        FastJsonHttpMessageConverter[] messageConverters = new FastJsonHttpMessageConverter[1];

        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();

        List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();

//        MediaType mediaType = new MediaType(MediaType.TEXT_HTML_VALUE);
        MediaType mediaType = MediaType.valueOf(MediaType.TEXT_HTML_VALUE);

        supportedMediaTypes.add(mediaType);

        fastJsonHttpMessageConverter.setSupportedMediaTypes(supportedMediaTypes);

        messageConverters[0] = fastJsonHttpMessageConverter;

        amha.setMessageConverters(messageConverters);

        return amha;
    }

    /**
     *
     * @return
     */
    @Bean
    public CommonsMultipartResolver multipartResolver() {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();

        multipartResolver.setDefaultEncoding("utf-8");

        multipartResolver.setMaxUploadSize(2048 * 1024);

        multipartResolver.setMaxInMemorySize(2048);

        return multipartResolver;
    }

}


javaConfig ComponentScan注解默认包是什么都没有,所以必须自己动手配置指定包(

@ComponentScan(basePackages = {"com.springmvc.service.impl","com.springmvc.dao.impl"}))

(org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.springmvc.controller.UserController.setUserService(com.springmvc.service.UserService); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.springmvc.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}


fastjson2.7.0和spring4.2.4不匹配,只要把fastjson版本降成2.6.5就行了
com.fasterxml.jackson.databind.type.TypeFactory.constructType(Ljava/lang/reflect/Type;Ljava/lang/Class;)Lcom/fasterxml/jackson/databind/JavaType;


事务管理器配置sessionFactory的时候虽然显示的是ref LocalSessionFactoryBean类对应的bean,但是实际上是ref了LocalSessionFactoryBean 中的sessionFactory属性,sessionFactory = getBean("LocalSessionFactoryBean").getObject()。

http://stackoverflow.com/questions/31281179/error-java-lang-illegalargumentexception-invalid-token-character-in-token



写junit测试用例的时候在没有为测试用例注解@WebAppConfiguration的基础上引入了Spring MVC的核心配置文件类报错:Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling

顾名思义,在没有注解@WebAppConfiguration的时候只要不引入spring mvc核心配置就能解决问题,当然了也可以引入@WebAppConfiguration:

http://www.4byte.cn/question/77524/java-lang-illegalargumentexception-a-servletcontext-is-required-to-configure-default-servlet-handling.html


import com.springmvc.po.User;
import com.springmvc.service.UserService;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.junit.Test;
import org.springframework.test.context.web.WebAppConfiguration;

/**
 * Created by baich on 2016/1/26.
 */

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {com.springmvc.config.ApplicationContext.class, com.springmvc.config.SpringServlet.class})
public class SpringTest {
    @Autowired
    private UserService userService;
    @Test
    public void save() {
        User user = new User();
        user.setName("yangbo");
        user.setGender("male");
        user.setDescribtion("javaConfig");
        userService.save(user);
    }
}

OR

import com.springmvc.po.User;
import com.springmvc.service.UserService;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.junit.Test;
import org.springframework.test.context.web.WebAppConfiguration;

/**
 * Created by baich on 2016/1/26.
 */

@RunWith(SpringJUnit4ClassRunner.class)
//@WebAppConfiguration
@ContextConfiguration(classes = {com.springmvc.config.ApplicationContext.class})
public class SpringTest {
    @Autowired
    private UserService userService;
    @Test
    public void save() {
        User user = new User();
        user.setName("yangbo");
        user.setGender("male");
        user.setDescribtion("javaConfig");
        userService.save(user);
    }
}


测试编写的时候如果不用注解形式获取bean而采用ApplicationContext的形式获取bean一定要注意getBean("")后强转为接口类型,不能强转为实现类类型,不然会报错:


代码

import com.sunsharing.po.User;
import com.sunsharing.service.impl.UserServiceImpl;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Created by baich on 2016/1/27.
 */
public class BaseTest {
    @Test
    public void test() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserServiceImpl userServiceImpl = (UserServiceImpl) ac.getBean("userService");
        User user = new User();
        user.setName("yangbo");
        user.setGender("male");
        user.setDescribtion("am a boy");
        userServiceImpl.save(user);

    }
}

错误

java.lang.ClassCastException: com.sun.proxy.$Proxy18 cannot be cast to com.sunsharing.service.impl.UserServiceImpl


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值