Intellij Idea搭建Spring环境-全注解(不用web.xml)

首先要创建一个普通的Maven Web项目,不需要web.xml,如果有的话直接删除。

特别注意:Spring在整合其他组件的时候,如果其他组件已引入了一些Spring的jar包(如spring-data-mongodb),要注意与项目使用的主版本最好一致,不然会因为依赖冲突导致一些奇奇怪怪的错误,如IMPORT_BEAN_NAME_GENERATOR。

所以选择组件版本不是越高越好,适合的就好(你要么就提高Spring版本,但是风险较大)。

pom.xml

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <spring.version>5.0.2.RELEASE</spring.version>
    <jackson.version>2.11.4</jackson.version>
</properties>

<dependencies>
    <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-aspects</artifactId>
        <version>${spring.version}</version>
    </dependency>

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

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

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

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
    </dependency>

    <!--Jackson-->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>${jackson.version}</version>
    </dependency>

</dependencies>

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <!--因为没有web.xml,所以打成war包的时候需要忽略掉,否则会提示没有web.xml-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>
</build>

Spring上下文配置

tomcat启动时会自动扫描继承AbstractAnnotationConfigDispatcherServletInitializer的文件,所以这个文件是整个项目的程序入口,在这里可以配置根容器、Spring MVC容器,拦截请求等。

import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.Filter;

/**
 * @Description 整个项目的程序入口
 */
public class SpringContainer extends AbstractAnnotationConfigDispatcherServletInitializer {

    /**
     * 根容器,用于获取Spring应用容器的配置文件
     *
     * @return
     */
    @Override
    protected Class<?>[] getRootConfigClasses() {
        //return new Class[0];
        return new Class[]{RootConfig.class};
    }

    /**
     * Spring mvc容器,是根容器的子容器
     *
     * @return
     */
    @Override
    protected Class<?>[] getServletConfigClasses() {
        //return new Class[0];
        return new Class[]{WebConfig.class};
    }

    /**
     * "/"表示由DispatcherServlet处理所有向该应用发起的请求。
     *
     * @return
     */
    @Override
    protected String[] getServletMappings() {
        //return new String[0];
        return new String[]{"/"};
    }

    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);
        return new Filter[]{characterEncodingFilter, characterEncodingFilter};
    }
}

RootConfig类

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

@Configuration
/**
 * @EnableAspectJAutoProxy:开启AOP代理自动配置
 * proxyTargetClass=true:表示使用CGLib动态代理技术织入增强,决定是基于接口的还是基于类的代理被创建。默认为false(JDK代理)
 * 即<aop:aspectj-autoproxy proxy-target-class="true"/>
 * */
@EnableAspectJAutoProxy(proxyTargetClass = true) //解决实现接口后,spring不能创建类实例的问题
@ComponentScan(
        basePackages = {"com.harvey"},
        excludeFilters = {//设置不扫描的文件,这里会排除Controller
                @ComponentScan.Filter(type = FilterType.ANNOTATION, value = RestController.class),
                @ComponentScan.Filter(type = FilterType.ANNOTATION, value = Controller.class)
        }
)
public class RootConfig {

}

WebConfig类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description Spring MVC 配置
 */
@Configuration
@EnableWebMvc   //启用Spring MVC组件
@ComponentScan("com.yyds.base.controller")  //配置扫描的ctrl层
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.viewResolver(viewResolver());
    }

    /**
     * 配置静态资源的处理
     *
     * @param configurer
     */
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        //把针对静态资源的请求转交给servlet容器的default servlet处理
        configurer.enable();
    }

    /**
     * Jackson配置
     * 添加自定义转换器
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(mappingJackson2HttpMessageConverter());
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //访问/hello/index,直接跳转到/WEB-INF/pages/index.jsp页面
        registry.addViewController("/hello/index2").setViewName("index");
    }

    /**
     * Jackson配置
     *
     * @return
     */
    @Bean
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
        //MediaType mediaType1 = new MediaType("application\\json");
        //MediaType mediaType2 = new MediaType("charset=UTF-8");
        //supportedMediaTypes.add(mediaType1);
        //supportedMediaTypes.add(mediaType2);

        supportedMediaTypes = MediaType.parseMediaTypes("application/json; charset=utf-8");

        converter.setSupportedMediaTypes(supportedMediaTypes);
        return converter;
    }

    /**
     * 配置JSP视图解析器
     *
     * @return
     */
    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/pages/");
        resolver.setSuffix(".jsp");
        //可以在JSP页面中通过${}访问beans
        resolver.setExposeContextBeansAsAttributes(true);
        return resolver;
    }
}

Spring环境验证

HelloController类

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/hello")
public class HelloController {

    /**
     * 直接返回字符串
     *
     * @param name
     * @return
     */
    @GetMapping("/say")
    @ResponseBody
    public String sayChinese(String name) {
        return "hello " + name;
    }

    /**
     * 跳转页面
     *
     * @return
     */
    @GetMapping("/index")
    public String index() {
        return "index";
    }
}

WEB-INF/pages/index.jsp

<html>
<body>
<h2>Hello World!</h2>
</body>
</html>

使用Tomcat进行项目发布,访问http://localhost:8080/hello/index或http://localhost:8080/hello/index2

 

posted @ 2023-11-19 21:19  残城碎梦  阅读(66)  评论(0编辑  收藏  举报