spring4.x以後,實作了零配置.其實就是把相關的配置檔案變成了配置類.以前的application.xml變成了
@Configuration
@EnableWebMvc
@ComponentScan
(
"com.youxiduo.annotation"
)
public
class
AnnoConfig
{
}
@Configuration 聲明這個類是配置類
@ComponentScan 對所有component(元件)的掃描,加載
@EnableWebMvc 開啟對webMvc的支援
上面隻是spring容器的配置類,那麼如何接受到前台的請求呢,這個就要實作spring對web.xml的實作
public
class
WebInitializer
implements
WebApplicationInitializer
{
@Override
public
void
onStartup
(
ServletContext
servletContext
)
throws
ServletException
{
AnnotationConfigWebApplicationContext
ctx
=
new
AnnotationConfigWebApplicationContext
();
ctx
.
register
(
AnnoConfig
.
class
);
ctx
.
setServletContext
(
servletContext
);//建立WebApplicationContext,注冊配置類,并将其和目前的servletContext關聯
//注冊sprigmvc的DispatcherServlet
ServletRegistration
.
Dynamic
servlet
=
servletContext
.
addServlet
(
"dispatcher"
,
new
DispatcherServlet
(
ctx
));
servlet
.
addMapping
(
"/"
);
servlet
.
setLoadOnStartup
(
1
);
}
}
WebApplicationInitializer 是spring提供用來配置Servlet3.0+配置接口,進而實作了替代web.xml的位置.實作接口将自動被SpringServletContainerInitializer(用來擷取Servlet3.0容器的)擷取到.
需要用到的兩個jar檔案
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<!--Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>