所谓的零配置是指将流行许久的xml配置用java类来替代,这样做的好处是防止客户对xml配置文件的修改。spring 3.0新增了WebApplicationInitializer接口,这个接口的实现类会被spring3.0以上的容器侦查到并自动启动。
首先,创建一个启动类WebInitializer,这个类等价于web.xml,需要实现onStartup方法。
public class WebInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfig.class);
ctx.setServletContext(servletContext);
ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
}
接下来写一个spring配置类,@Configuration注解告诉容器这是一个spring配置类, @ComponentScan配置包扫描,@EnableWebMvc表示使用web mvc。类中配置了两个Bean, freeMarkerViewResolver、freeMarkerConfig。freeMarkerViewResolver,freemarker视图解析类。
@Configuration
@ComponentScan(basePackageClasses = WebConfig.class)
@EnableWebMvc
public class WebConfig {
@Bean
public FreeMarkerViewResolver freeMarkerViewResolver() {
FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
resolver.setSuffix(".ftl");
resolver.setContentType("text/html; charset=UTF-8");
resolver.setViewClass(FreeMarkerView.class);
resolver.setExposeSpringMacroHelpers(false);
resolver.setExposeRequestAttributes(true);
resolver.setAllowRequestOverride(true);
return resolver;
}
@Bean
public FreeMarkerConfigurer getFreemarkerConfig() {
FreeMarkerConfigurer result = new FreeMarkerConfigurer();
result.setTemplateLoaderPath("WEB-INF/templates/"); //模板位置
return result;
}
}
这样一个简单的零配置就完成了。
接下来写个Controller验证下
@Controller
public class HelloController {
@RequestMapping(value = "/hello/say", method = RequestMethod.GET)
public String sayHello() {
return "hello";
}
}
freemarker模板结构