使用@Configuration注解配置类,实现spring MVC无web.xml配置.
1. project环境
IDE: eclipse
JDK: 1.7
Server: tomcat7.0
2. 使用maven创建webapp, project Web Module 3.0
3. project的pom文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.homeway</groupId> <artifactId>testPrj</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>testPrj Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <spring.version>4.1.5.RELEASE</spring.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> </dependency> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.3</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>18.0</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.3.2</version> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.8.3</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.1</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.34</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> </dependencies> <build> <finalName>testPrj</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> </plugins> </build> </project>
4. 编写类, 实现WebApplicationInitializer接口. 这个动作就相当于配置web.xml
这个类的主要作用包含:
(1) 获取spring的配置信息,等同于web.xml中为ContextLoaderListener配置spring的applicationContext.xml
(2) 配置servlet和filter. 如配置spring的DispatcherServlet
package org.homeway.testPrj.springmvc; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; public class WebInit implements WebApplicationInitializer { Logger logger = LoggerFactory.getLogger(WebInit.class); @Override public void onStartup(ServletContext servletContext) throws ServletException { /* * ContextLoaderListener is added to ServletContext – * the purpose of this is to 'glue' WebApplicationContext * to the lifecycle of ServletContext */ WebApplicationContext context = getContext(); servletContext.addListener(new ContextLoaderListener(context)); /* * DispatcherServlet is created and initialized with * WebApplicationContext we have created, and it's * mapped to "/*" URLs and set to eagerly load on * application startup. */ ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/"); } private AnnotationConfigWebApplicationContext getContext() { /* * AnnotationConfigWebApplicationContext is created. * It's WebApplicationContext implementation that * looks for Spring configuration in classes annotated * with @Configuration annotation. * setConfigLocation() method gets hint in which * package(s) to look for them. */ AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); context.scan("org.homeway.testPrj.springmvc.config"); return context; } }
5. 编写类, 配置spring
这个类包含了:
(1) bean的实例化与注入
(2) ComponentScan的配置
如何配置与读取porperties文件, 参考代码.
package org.homeway.testPrj.springmvc.config; import javax.annotation.Resource; import org.apache.tomcat.dbcp.dbcp.BasicDataSource; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.view.JstlView; import org.springframework.web.servlet.view.UrlBasedViewResolver; /* * The main AppConfig configuration class doesn't do anything * but hits Spring on where to look for its components through * @ComponentScan annotation. */ @Configuration @EnableWebMvc @ComponentScan(basePackages = "org.homeway.testPrj") @PropertySource("classpath:application.properties") public class AppConfig { @Resource Environment env; @Bean(name="viewResolver") public UrlBasedViewResolver setupViewResolver() { UrlBasedViewResolver viewResolver = new UrlBasedViewResolver(); viewResolver.setPrefix("/WEB-INF/views/"); viewResolver.setSuffix(".jsp"); viewResolver.setViewClass(JstlView.class); viewResolver.setOrder(0); return viewResolver; } @Bean(name="dataSource") public BasicDataSource setupDataSource() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(env.getProperty("db.driver")); dataSource.setUrl(env.getProperty("db.url")); dataSource.setUsername(env.getProperty("db.user")); dataSource.setPassword(env.getProperty("db.pwd")); return dataSource; } @Bean(name="jdbcTemplate") public JdbcTemplate setupJdbcTemplate( @Qualifier("dataSource")BasicDataSource dataSource) { return new JdbcTemplate(dataSource); } @Bean(name="dataSourceTransactionManager") public DataSourceTransactionManager setDataSourceTransactionManager(BasicDataSource dataSource){ DataSourceTransactionManager tm = new DataSourceTransactionManager(); tm.setDataSource(dataSource); return tm; } }
6. 编写类, 继承WebMvcConfigurerAdapter类.
这个类提供了许多void方法,复写这些方法以实现具体的配置
package org.homeway.testPrj.springmvc.config; import java.util.List; import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.HandlerMethodReturnValueHandler; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer; import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.ViewResolverRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /* * WebMvcConfig class enables Spring MVC with @EnableWebMvc annotation. * It extends WebMvcConfigurerAdapter, which provides empty methods * that can be overridden to customize default configuration of Spring * MVC. We will stick to default configuration at this time, but it’s * advised for you to see what the possibilities are. */ @Configuration @EnableWebMvc public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { //<mvc:resources mapping="/resources/**" location="/public-resources/"/> registry.addResourceHandler("resources/**").addResourceLocations("/public-resources"); } @Override public void addInterceptors(InterceptorRegistry registry) { // TODO Auto-generated method stub super.addInterceptors(registry); } @Override public void addArgumentResolvers( List<HandlerMethodArgumentResolver> argumentResolvers) { // TODO Auto-generated method stub super.addArgumentResolvers(argumentResolvers); } @Override public void addFormatters(FormatterRegistry registry) { // TODO Auto-generated method stub super.addFormatters(registry); } @Override public void addReturnValueHandlers( List<HandlerMethodReturnValueHandler> returnValueHandlers) { // TODO Auto-generated method stub super.addReturnValueHandlers(returnValueHandlers); } @Override public void addViewControllers(ViewControllerRegistry registry) { // TODO Auto-generated method stub super.addViewControllers(registry); } @Override public void configureMessageConverters( List<HttpMessageConverter<?>> converters) { // TODO Auto-generated method stub super.configureMessageConverters(converters); } @Override public void extendMessageConverters(List<HttpMessageConverter<?>> converters) { // TODO Auto-generated method stub super.extendMessageConverters(converters); } @Override public void configureAsyncSupport(AsyncSupportConfigurer configurer) { // TODO Auto-generated method stub super.configureAsyncSupport(configurer); } @Override public void configureContentNegotiation( ContentNegotiationConfigurer configurer) { // TODO Auto-generated method stub super.configureContentNegotiation(configurer); } @Override public void configureDefaultServletHandling( DefaultServletHandlerConfigurer configurer) { // TODO Auto-generated method stub super.configureDefaultServletHandling(configurer); } @Override public void configureHandlerExceptionResolvers( List<HandlerExceptionResolver> exceptionResolvers) { // TODO Auto-generated method stub super.configureHandlerExceptionResolvers(exceptionResolvers); } @Override public void configurePathMatch(PathMatchConfigurer configurer) { // TODO Auto-generated method stub super.configurePathMatch(configurer); } @Override public void configureViewResolvers(ViewResolverRegistry registry) { // TODO Auto-generated method stub super.configureViewResolvers(registry); } }
7. 编写测试代码
(略)
8. 附件
相关推荐
2. **Spring Beans**:定义了Bean的配置方式,支持XML、注解及Java配置。 3. **Spring AOP**:实现了面向切面编程,允许定义方法拦截器和切入点表达式。 4. **Spring MVC**:用于构建Web应用的Model-View-...
【标题】"MyEclipse for Spring Demo Project" 是一个基于MyEclipse集成开发环境和Spring框架的示例项目,旨在帮助开发者了解如何在MyEclipse中配置和开发Spring应用程序。这个项目展示了如何利用MyEclipse的工具集...
总结起来,Spring Boot和MyBatis的结合使用可以简化Web应用的开发,而MyBatis Generator则进一步提升了开发效率,通过自动化生成DAO接口和XML配置文件,使开发者能够更专注于业务逻辑的实现。在实际开发中,理解并...
虽然本示例是XML配置,但Spring还支持基于注解的配置,如@Service、@Component、@Repository和@Controller,这些注解可以替代XML配置,简化代码。 9. **集成环境** 文件`.classpath`、`.mymetadata`、`.project`...
虽然这里的示例没有XML配置,但在实际项目中,可能会需要使用到。 最后,为了让Spring Boot能够自动扫描并注册Mapper,我们需要配置`@MapperScan`注解在主配置类上: ```java import org.mybatis.spring.annotation...
- `web.xml`是Spring MVC的核心配置文件之一,主要用于声明servlet的清单。 - 需要在`web.xml`中配置`DispatcherServlet`,这是Spring MVC的核心组件,负责接收前端请求并将请求分发给相应的控制器处理。 - 如果...
标题中的"wa-spring1-SpringProject.zip_spring mvc 例子"表明这是一个关于Spring MVC框架的实际应用示例项目。Spring MVC是Spring框架的一个模块,主要用于构建Web应用程序,它提供了模型-视图-控制器(MVC)架构...
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> ``` 4. **创建Spring MVC...
- `webapp/WEB-INF`: 可能包含Spring Security的web配置,如web.xml。 这个示例项目应该会包含一个示例的用户界面,展示如何登录、如何根据角色访问受限页面,以及如何进行权限控制。通过分析源代码,你可以学习...
9. **Web.xml**:虽然Spring Portlet MVC主要在portlet.xml中配置,但在传统的Web应用中,`web.xml`可能仍然用于定义servlet容器的配置,例如filter和listener。 在实际开发中,这个示例项目可以帮助理解Spring ...
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> ``` 现在,我们可以在...
在`src/main/resources`目录下创建`beans.xml`文件,用于XML配置,或者创建`@Configuration`注解的Java类进行Java配置。 XML配置示例: ```xml <bean id="exampleBean" class="com.example.ExampleBean"> ``` ...
3. **配置Web.xml**:配置Struts和Spring的前端控制器,例如`struts-config.xml`和`web.xml`。在`web.xml`中,你需要定义DispatcherServlet以及Spring的监听器`ContextLoaderListener`。 4. **编写Action类**:创建...
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> ``` 然后,你需要在web...
在本文中,我们将深入探讨如何在Eclipse集成开发环境中配置Spring MVC框架,以实现一个简单的登录页面示例。Spring MVC是Spring框架的一部分,它提供了一种模型-视图-控制器(MVC)架构来构建Web应用程序。让我们一...
<bean class="org.springframework.web.context.support.AnnotationConfigWebApplicationContext"> <property name="configLocation" value="com.yourpackage.config"> ``` 3. **Hibernate 配置** - 添加 ...
- **src/main/resources**:存放配置文件,如Spring的bean配置、MyBatis的mapper XML文件、数据库连接配置等。 - **src/main/webapp**:Web应用的根目录,包括WEB-INF目录下的web.xml(Web应用的部署描述符),...
<servlet-class>org.springframework.web.servlet.DispatcherServlet <param-name>contextConfigLocation <param-value>/WEB-INF/applicationContext.xml <load-on-startup>1 <servlet-name>...
然而,随着Spring的发展,特别是Spring 3.0引入了基于注解的配置,XDoclet的这部分功能逐渐被Spring自身的注解取代,如`@Controller`、`@RequestMapping`等。 最后,虽然XDoclet在过去是提高开发效率的有效工具,但...