Spring MVC4 纯注解配置教程

阅读本文需要又一定的sping基础,最起码要成功的运行过一个SpringMvc项目。

在传统的Spring项目中,我们要写一堆的XML文件。而这些XML文件格式要求又很严格,很不便于开发。而网上所谓的0配置,并不是纯粹的0配置,还是要写一些xml配置,只是用了几个@Service,@Controller注解而已。

在这里,我讲介绍一种新的配置方式,一行XML代码都不需要,什么web.xml,Application-context.xml,Beans.xml,统统去死吧!

 

首先建立一个Maven项目,Packageing方式为war,项目结构为标准Maven WebApp结构。

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.0modelVersion>
    <groupId>com.csonezpgroupId>
    <artifactId>springdemoartifactId>
    <packaging>warpackaging>
    <version>1.0-SNAPSHOTversion>
    <name>dataplatform Maven Webappname>
    <url>http://maven.apache.orgurl>
    <properties>
        <spring.version>4.0.1.RELEASEspring.version>
    properties>
    <dependencies>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.11version>
        dependency>

        
        <dependency>
            <groupId>asmgroupId>
            <artifactId>asm-commonsartifactId>
            <version>2.2.3version>
        dependency>
        <dependency>
            <groupId>asmgroupId>
            <artifactId>asmartifactId>
            <version>2.2.3version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-coreartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-ormartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-aopartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-expressionartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-txartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>${spring.version}version>
        dependency>


        <dependency>
            <groupId>cglibgroupId>
            <artifactId>cglibartifactId>
            <version>2.2.2version>
        dependency>
        
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>javax.servlet-apiartifactId>
            <version>3.0.1version>
            <scope>providedscope>
        dependency>
        <dependency>
            <groupId>jstlgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>

        <dependency>
            <groupId>org.codehaus.jacksongroupId>
            <artifactId>jackson-core-aslartifactId>
            <version>1.8.4version>
        dependency>

        <dependency>
            <groupId>org.codehaus.jacksongroupId>
            <artifactId>jackson-mapper-aslartifactId>
            <version>1.8.4version>
        dependency>

        <dependency>
            <groupId>c3p0groupId>
            <artifactId>c3p0artifactId>
            <version>0.9.1.2version>
        dependency>


        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>1.2.8version>
        dependency>


        <dependency>
            <groupId>org.jsongroupId>
            <artifactId>jsonartifactId>
            <version>20090211version>
        dependency>


        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.6version>
        dependency>

        <dependency>
            <groupId>spygroupId>
            <artifactId>spymemcachedartifactId>
            <version>2.6version>
        dependency>

        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-apiartifactId>
            <version>1.6.6version>
        dependency>
    dependencies>
    <build>
        <finalName>dataplatformfinalName>
    build>
project>

 

这个时候,就该进行Spring配置了。按传统方式来的话,首先要去web.xml写一堆配置,然后建立个管理beab的Beans.xml,管理spring mvc 的xml,再写一坨一坨Bean。就是先进一点的(也就是很多人说的0配置),也就是自己的业务Bean不用写进xml了,还是很麻烦。

而我这里讲的方式,则是完全不修改任何web.xml代码,不写一行XML代码的方式。

 

首先,在项目立建立一个Config.java文件:

**
 * Created by zhangpeng on 16-3-22.
 * 取代Beans.xml,纯注解配置各种BEAN
 */
@Configuration
@ComponentScan("com.csonezp")
@EnableWebMvc
public class Config {
    /**
     * jsp视图解析器的bean
     * @return
     */
    @Bean
    public UrlBasedViewResolver setupViewResolver() {
        UrlBasedViewResolver resolver = new UrlBasedViewResolver();
        resolver.setPrefix("/WEB-INF/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);
        return resolver;
    }

    /**
     * 配置数据源
     * @return
     */
    @Bean(name = "dataSource")
    public ComboPooledDataSource getDataSource() {
        try {

            ComboPooledDataSource dataSource = new ComboPooledDataSource();
            dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/mfdb");
            dataSource.setDriverClass("com.mysql.jdbc.Driver");
            dataSource.setUser("root");
            dataSource.setPassword("zp1228");
            dataSource.setMaxPoolSize(75);
            return dataSource;
        } catch (Exception e) {
            return null;
        }
    }
}

 

@Configuration注解就是告诉Spring这个是一个配置文件类,这里配置的Bean要交给Spring去管理。这个就是用来取代Beans.xml这种文件的。

@ComponentScan("com.csonezp")这个注解就是配置包扫描用的,不必多说了

@EnableWebMvc ,启用Spring MVC支持

 

这里面配置了两个Bean,第一个就是JSP的视图解析器,第二个则是配置了一个数据源。这些都可以对应到XML文件里面去的。找一个传统Spring项目,用xml文件对比着我这个类去看,会对这种配置方式有更深的了解。

 

下面要建立一个WebInitializer类继承WebApplicationInitializer,在这里添加一个servlet。这一步是用来取代在web.xml中添加servlet的步骤

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;

public class WebInitializer implements WebApplicationInitializer {

    public void onStartup(ServletContext servletContext) throws ServletException {
          
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(Config.class);  
        ctx.setServletContext(servletContext);    
        
        Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
        servlet.addMapping("/");  
        servlet.setLoadOnStartup(1);  
          
    }  

}

这样就OK啦!让我们写一些代码来测试一下吧!

import org.springframework.stereotype.Service;

/**
 * Created by zhangpeng on 16-3-22.
 */
@Service
public class HelloService {
    public String getHello(String name) {
        return name + ",Hello!";
    }
}
import com.guduo.dataplatform.service.HelloService;
import com.guduo.dataplatform.service.MovieService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Created by zhangpeng on 16-3-22.
 */
@Controller
@RequestMapping("/test")
public class TestController {

    @Autowired
    HelloService helloService;
    @Autowired
    MovieService movieService;


    @RequestMapping("/hello")
    public String sayHello(@RequestParam("name") String name, ModelMap model) {
        model.put("hello", helloService.getHello(name));
        return "hello";
    }
}

一个service,一个controller。

启动项目,在浏览器中输入地址http://localhost:8080/dp/test/hello?name=sss

页面显示sss,Hello!

完工!

 

额,忘了演示Confgig里配置的bean如何使用了。其实和XML里的一样。这里拿一个DAO做演示吧,这里就注入了我们在config里配置的那个数据源

@Repository
public class MoviePlayIncDao {
    private DataSource dataSource;

    private JdbcTemplate jdbcTemplateObject;

    @Autowired
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
        this.jdbcTemplateObject = new JdbcTemplate(dataSource);
    }

    public List getMoviePlayInc(int movieId) {
        try {
            String SQL = "select * from movieplayincreament where movieid=?";
            List list = jdbcTemplateObject.query(SQL, new MoviePlayIncMapper(), new Object[]{movieId});
            return list;
        } catch (Exception e) {
            return null;
        }
    }


}

 

转载于:https://www.cnblogs.com/csonezp/p/5315725.html

你可能感兴趣的:(Spring MVC4 纯注解配置教程)