前些天發現了一個巨牛的人工智能學習網站,通俗易懂,風趣幽默,忍不住分享一下給大家。點擊跳轉到教程。
怎么樣去理解它呢?
1.配置視圖控制器
- package?com.apress.prospringmvc.bookstore.web.config;??
- import?org.springframework.web.servlet.config.annotation.ViewControllerRegistry;??
- import?org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;??
- ??
- @Configuration??
- @EnableWebMvc??
- @ComponentScan(basePackages?=?{?"com.apress.prospringmvc.bookstore.web"?})??
- public?class?WebMvcContextConfiguration?extends?WebMvcConfigurerAdapter?{??
- ??
- ????@Override??
- ????public?void?addViewControllers(final?ViewControllerRegistry?registry)?{??
- ????????registry.addViewController("/index.htm").setViewName("index");??
- ????}??
- }??
2.基于注解的Controller
?
- package?com.apress.prospringmvc.bookstore.web;??????
- import?org.springframework.stereotype.Controller;??????
- import?org.springframework.web.bind.annotation.RequestMapping;??????
- import?org.springframework.web.servlet.ModelAndView;??????
- @Controller??????
- public?class?IndexController?{??????
- @RequestMapping(value?=?"/index.htm")??????
- ????public?ModelAndView?indexPage()?{???????
- ????????return?new?ModelAndView(“index");??????
- ????}??????
- }?????
?
那么對于配置的視圖控制器加了
@Configuration 和@ComponentScan注解背后會做什么呢?
?
其實很簡單,@ComponentScan告訴Spring 哪個packages 的用注解標識的類 會被spring自動掃描并且裝入bean容器。
例如,如果你有個類用@Controller注解標識了,那么,如果不加上@ComponentScan,自動掃描該controller,那么該Controller就不會被spring掃描到,更不會裝入spring容器中,因此你配置的這個Controller也沒有意義。
類上的注解@Configuration 是最新的用注解配置spring,也就是說這是個配置文件,和原來xml配置是等效的,只不過現在用java代碼進行配置了 加上一個@Configuration注解就行了,是不是很方便,不需要那么繁瑣的xml配置了,這樣基于注解的配置,可讀性也大大增高了。
?
見:http://blog.csdn.net/u013078669/article/details/52664779