纯java配置springmvc, spring, mybatis

本文详细介绍如何使用Java配置方式搭建SSM(Spring+SpringMVC+MyBatis)框架环境,包括配置类的创建、依赖引入、拦截器、视图解析器、静态资源处理等关键步骤。

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

使用纯 Java 来搭建 SSM 环境,idea工具,jdk1.8,要求 Tomcat 的版本必须在 7 以上。

一、添加pom.xml坐标

 <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet.api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
 </dependencies>

二、初始化spring, springmvc的java类

目录结构

1.Spring配置的java类 SpringConfig

/**
 * spring的配置文件
 */
@Configuration
@ComponentScan(basePackages = "com.fang", useDefaultFilters = true, excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Controller.class)})
public class SpringConfig {
}

2.springmvc配置的java类 SpringMVCConfig

/**
 * springmvc配置文件
 */
@Configuration
@ComponentScan(basePackages = "com.fang")
public class SpringMVCConfig extends WebMvcConfigurationSupport {
}

注解:
@Configuration 注解表示这是一个配置类,在我们这里,这个配置的作用类似于 applicationContext.xml
@ComponentScan 注解表示配置包扫描,里边的属性和 xml 配置中的属性都是一一对应的, useDefaultFilters 表示使用默认的过滤器,然后又除去 Controller 注解,即在 Spring 容器中扫描除了 Controller 之外的其他所有 Bean 。
其中: Controller需要导入注解的包, 不能导入接口包

3.配置 web.xml 的java类 WebInit

/**
 * 初始化mvc   相当于web.xml
 */
public class WebInit implements WebApplicationInitializer {
    public void onStartup(ServletContext servletContext) throws ServletException {
        //首先来加载 SpringMVC 的配置文件
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(SpringMVCConfig.class);
        // 添加 DispatcherServlet
        ServletRegistration.Dynamic springmvc = servletContext.addServlet("springmvc", new DispatcherServlet(ctx));
        // 给 DispatcherServlet 添加路径映射
        springmvc.addMapping("/");
        // 给 DispatcherServlet 添加启动时机
        springmvc.setLoadOnStartup(1);
    }
}

这样就可以完成测试springmvc的使用

@RestController
public class HelloController {
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }
}

三. springmvc的配置类需要继承WebMvcConfigurationSupport类

springmvc的配置类中可以添加各种springmvc.xml中的属性。如: 静态资源过滤、视图解析器、路径映射等等。
WebMvcConfigurerAdapter使用方式
1、过时方式:继承WebMvcConfigurerAdapter
Spring 5.0 以后WebMvcConfigurerAdapter会取消掉
WebMvcConfigurerAdapter是实现WebMvcConfigurer接口

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
//TODO
}

2、现在方式
实现WebMvcConfigurer

@Configuration
public class WebMvcConfg implements WebMvcConfigurer {
//TODO
}

继承WebMvcConfigurationSupport

@Configuration
public class WebMvcConfg extends WebMvcConfigurationSupport {
//TODO
}
WebMvcConfigurationSupport详解

WebMvcConfigurerAdapter常用的方法

/** 解决跨域问题 **/
public void addCorsMappings(CorsRegistry registry) ;

/** 添加拦截器 **/
void addInterceptors(InterceptorRegistry registry);

/** 这里配置视图解析器 **/
void configureViewResolvers(ViewResolverRegistry registry);

/** 配置内容裁决的一些选项 **/
void configureContentNegotiation(ContentNegotiationConfigurer configurer);

/** 视图跳转控制器 **/
void addViewControllers(ViewControllerRegistry registry);

/** 静态资源处理 **/
void addResourceHandlers(ResourceHandlerRegistry registry);

/** 默认静态资源处理器 **/
void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer);
  1. addCorsMappings:跨域
   @Override
   public void addCorsMappings(CorsRegistry registry) {
   	super.addCorsMappings(registry);
   	registry.addMapping("/**")
   		.maxAge(3600)
   		.allowCredentials(true)
   		.allowedOrigins("*")
   		.allowedHeaders("*")
   		.allowedMethods("GET","POST","OPTIONS","HEAD","PUT")
   		.exposedHeaders("Content-Disposition");
   }
  1. addInterceptors:拦截器
addInterceptor:需要一个实现HandlerInterceptor接口的拦截器实例
addPathPatterns:用于设置拦截器的过滤路径规则
excludePathPatterns:用于设置不需要拦截的过滤规则

@Override
public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(this.authInterceptor)
			.addPathPatterns("/**")
			.excludePathPatterns("/auth/**","/v2/**","/swagger-resources/**","/swagger-ui.html#!/**");
		registry.addInterceptor(this.apiPassInterceptor)
			.addPathPatterns("/**")
			.excludePathPatterns("/auth/**","/v2/**","/swagger-resources/**","/swagger-ui.html#!/**");
		super.addInterceptors(registry);
}
  1. configureViewResolvers:视图解析器
@Override
	public void configureViewResolvers(ViewResolverRegistry registry) {
		InternalResourceViewResolver jspRv=new InternalResourceViewResolver();
		jspRv.setPrefix("/WEB-INF/jsp/");
		jspRv.setSuffix(".jsp");
		registry.viewResolver(jspRv);
		super.configureViewResolvers(registry);
	}
  1. addViewControllers:跳转指定页面
@Override
 public void addViewControllers(ViewControllerRegistry registry) {
     super.addViewControllers(registry);
     registry.addViewController("/").setViewName("/index");
     //实现一个请求到视图的映射,而无需书写controller
     registry.addViewController("/login").setViewName("forward:/index.html");  
}
  1. configureMessageConverters:信息转换器
需要添加pom坐标
		<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.49</version>
        </dependency>
        
JSON 配置, 这样就可以在接口中直接返回 JSON 了,此时的 JSON 数据将通过 fastjson 生成。
	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		MappingJackson2HttpMessageConverter mj2hm=new MappingJackson2HttpMessageConverter();
		List<MediaType> mt_lst=new ArrayList<MediaType>();
		final Map<String,String> paramMap=new HashMap<String,String>();
		paramMap.put("charset", "UTF-8");
		mt_lst.add(new MediaType("application", "json", paramMap));
		mj2hm.setSupportedMediaTypes(mt_lst);
		converters.add(mj2hm);
		super.configureMessageConverters(converters);
	}
  1. addResourceHandlers:静态资源
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
		registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
		super.addResourceHandlers(registry);
	}

四. WebInit的配置类需要继承WebApplicationInitializer类

 	@Override
    public void onStartup(ServletContext servletContext)
			throws ServletException {
		servletContext.addListener(IntrospectorCleanupListener.class);
		servletContext.addListener(RequestContextListener.class);
		servletContext.addListener(org.apache.logging.log4j.web.Log4jServletContextListener.class);
		
		javax.servlet.FilterRegistration.Dynamic freg=servletContext.addFilter("characterEncodingFilter", CharacterEncodingFilter.class);
		Map<String,String> fpam=new HashMap<String,String>();
		fpam.put("encoding", "UTF-8");
		fpam.put("forceEncoding", "true");
		freg.setInitParameters(fpam);
		freg.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "*.action");
		
		/* Load Spring web application configuration */
		AnnotationConfigWebApplicationContext acwac = new AnnotationConfigWebApplicationContext();
		acwac.register(RootContextConfig.class);
		acwac.register(MvcWebConfig.class);
		acwac.setServletContext(servletContext);	/* necessary! */
		acwac.refresh();
		
		/* Create DispatcherServlet */
	    DispatcherServlet dispatcherServlet = new DispatcherServlet(acwac);
	    
	    /* Register and map the Servlet */
		ServletRegistration.Dynamic registration = servletContext.addServlet("dispatcherServlet", dispatcherServlet);
		registration.setLoadOnStartup(1);
		registration.addMapping("*.action",
				"/v2/api-docs",
				"/swagger-resources/configuration/security",
				"/swagger-resources/configuration/ui",
				"/swagger-resources");
		
    }

五、mybatis配置的java类 DataBaseConfig

@Configuration
@EnableWebMvc
//@MapperScan()
public class DataBaseConfig implements EnvironmentAware {
	/**
     * 数据资源配置
     * @return
     */
    @Bean
  	public BasicDataSource dataSource() {
        BasicDataSource dataSource = new BasicDataSource();
         dataSource.setDriverClassName("com.mysql.jdbc.Driver");
         dataSource.setUrl("jdbc:mysql://localhost:3306/hotel?useUnicode=true&characterEncoding=UTF-8");
         dataSource.setUsername("root");
         dataSource.setPassword("112233");
         return dataSource;
     }

     /**
      * mybatis配置
      * @return
      */
     @Bean
     public SqlSessionFactoryBean sqlSessionFactoryBean() {
         PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
         SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
         sqlSessionFactoryBean.setDataSource(dataSource());
         try {
             sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:com/gede/dao/*.xml"));
         } catch (IOException e) {
             e.printStackTrace();
         }
         return sqlSessionFactoryBean;
     }

	/**
	 * 加入事务
	 * @return
	 */
	@Bean
	public DataSourceTransactionManager transactionManager(DataSource sysDataSource) {
		return new DataSourceTransactionManager(sysDataSource);
	}

     /**
      * mybatis配置
      * @return
      */
     @Bean
     public MapperScannerConfigurer mapperScannerConfigurer() {
         MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
         mapperScannerConfigurer.setBasePackage("com.fang.dao");
         mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
         return mapperScannerConfigurer;
     }
}

事务处理

@Aspect
@Configuration
public class TransactionAdviceConfig {

	@Bean
	public Advisor txAdviceAdvisor(PlatformTransactionManager transactionManager) {
		AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
		pointcut.setExpression("execution(* com.fang.service..*(..))");
		return new DefaultPointcutAdvisor(pointcut, txAdvice(transactionManager));
	}
	
	@Bean
	public TransactionInterceptor txAdvice(PlatformTransactionManager transactionManager) {
		DefaultTransactionAttribute txAttr_REQUIRED = new DefaultTransactionAttribute();
		txAttr_REQUIRED.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

		DefaultTransactionAttribute txAttr_REQUIRED_READONLY = new DefaultTransactionAttribute();
		txAttr_REQUIRED_READONLY.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		txAttr_REQUIRED_READONLY.setReadOnly(true);

		NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
		source.addTransactionalMethod("*", txAttr_REQUIRED);
		source.addTransactionalMethod("get*", txAttr_REQUIRED_READONLY);
		source.addTransactionalMethod("query*", txAttr_REQUIRED_READONLY);
		source.addTransactionalMethod("select*", txAttr_REQUIRED_READONLY);
		return new TransactionInterceptor(transactionManager, source);
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值