1.创建一个maven工程javassm,流程同上一篇博客。
2.打开pom文件,默认选择Enable Auto Import ,自动导入关联依赖。程序打成war包,并引入spring mvc依赖
创建两个配置文件springConfig和SpringMVCConfig,作用和上一篇中xml文件相同,扫描目录下文件注入容器
package org.javaboy.config;
/**
* 这里默认扫描org.javaboy,但是controller除外
*/
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;
@Configuration
@ComponentScan(basePackages = "org.javaboy",useDefaultFilters = true,excludeFilters = {@ComponentScan.Filter
(type= FilterType.ANNOTATION,classes = Controller.class)})
public class SpringConfig {
}
package org.javaboy.config;
/**
* 这里默认不扫描org.javaboy,但是扫描Controller
*
*
*/
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;
@Configuration
@ComponentScan(basePackages = "org.javaboy",useDefaultFilters = false,includeFilters = {@ComponentScan.Filter(type =
FilterType.ANNOTATION,classes = Controller.class)})
public class SpringMVCConfig {
}
这里我们创建WebbInit来代替原本的web.xml,加载Spring MVC的配置,添加servlet和mapping并启动。这里需要实现接口
WebApplicationInitializer,并实现默认的方法onStartup,但是这里servlet报错了,所以我们需要引入依赖
创建HelloController和 HelloService来验证我们的配置是否有问题
package org.javaboy.controller;
import org.javaboy.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelleoController {
@Autowired
HelloService helloService;
//produces = "text/html;charset = utf-8" 使返回的中文避免乱码
@GetMapping(value = "/hello",produces = "text/html;charset = utf-8")
public String hello(){
return helloService.sayHello();
}
}
package org.javaboy.service;
import org.springframework.stereotype.Service;
@Service
public class HelloService {
public String sayHello() {
return "hello 极客技术";
}
}
部署之后运行,我们发现报错了。(如何部署参照上一篇详细步骤)
查看报错日志发现是无法创建service,翻看之前的weninit配置文件中,确实只有springMVC的配置没有spring的配置也就是只扫描了controller,所以我们需要修改SpringMVCConfig文件,增加对Configuration的扫描
然后重新运行程序