首頁 > 軟體

Spring MVC4 純註解設定教學

2020-06-16 17:27:16

閱讀本文需要有一定的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.0</modelVersion>
    <groupId>com.csonezp</groupId>
    <artifactId>springdemo</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>dataplatform Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <spring.version>4.0.1.RELEASE</spring.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>

        <!-- Spring dependencies -->
        <dependency>
            <groupId>asm</groupId>
            <artifactId>asm-commons</artifactId>
            <version>2.2.3</version>
        </dependency>
        <dependency>
            <groupId>asm</groupId>
            <artifactId>asm</artifactId>
            <version>2.2.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</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-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>


        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2.2</version>
        </dependency>
        <!-- Servlet API, JSTL -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>1.8.4</version>
        </dependency>

        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.8.4</version>
        </dependency>

        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>


        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.8</version>
        </dependency>


        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20090211</version>
        </dependency>


        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

        <dependency>
            <groupId>spy</groupId>
            <artifactId>spymemcached</artifactId>
            <version>2.6</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.6</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>dataplatform</finalName>
    </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<MoviePlayIncreament> getMoviePlayInc(int movieId) {
        try {
            String SQL = "select * from movieplayincreament where movieid=?";
            List<MoviePlayIncreament> list = jdbcTemplateObject.query(SQL, new MoviePlayIncMapper(), new Object[]{movieId});
            return list;
        } catch (Exception e) {
            return null;
        }
    }


}

本文永久更新連結地址http://www.linuxidc.com/Linux/2016-11/137551.htm


IT145.com E-mail:sddin#qq.com