使用弹簧怎么创建一个网站应用

  介绍

使用弹簧怎么创建一个网站应用?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

<强> Maven依赖

首先,我们需要引用spring-boot-starter-web依赖:

& lt; dependency>   & lt;才能groupId> org.springframework.boot</groupId>   & lt;才能artifactId> spring-boot-starter-web</artifactId>   & lt;才能version> 2.1.1.RELEASE</version>   & lt;/dependency>

该依赖包含:

<李>

Spring Web应用程序所需的Spring Web和spring-webmvc模块

<李>

Tomcat容器,这样我们就可以直接运行网络应用程序,而无需安装Tomcat

<>强创建一个弹簧引导应用程序

使用弹簧启动的最直接的方法是创建一个主类,并添加@SpringBootApplication注解:

@SpringBootApplication   public  class  SpringBootRestApplication  {   public 才能;static  void  main (String [], args), {   ,,,SpringApplication.run (SpringBootRestApplication.class, args);   ,,}   }

此单个注释等效于使用@ configuration, @EnableAutoConfiguration和@ComponentScan。

默认情况下,它将扫描本包和它的子包中的所有组件。

接下来,对于基于Java的Spring Bean配置,我们需要创建一个配置类,并使用@ configuration注解:

@ configuration   public  class  WebConfig  {   ,   }

该注解是春天主要使用的配置。它本身使用@ component进行元注解,这使注解的类成为标准豆,因此也成为组件扫描时的候选对象。

让我们看看使用核心spring-webmvc库的方法。

<强>使用spring-webmvc <强>

<强> Maven依赖

首先,我们需要引用spring-webmvc依赖:

& lt; dependency>   & lt;才能groupId> org.springframework</groupId>   & lt;才能artifactId> spring-webmvc</artifactId>   & lt;才能version> 5.0.0.RELEASE</version>   & lt;/dependency>

<>强基于java的Web配置

@ configuration   @EnableWebMvc   @ComponentScan (=basePackages “com.qulingfeng.controller")   public  class  WebConfig  {   ,,   }

在这里与弹簧引导的方式不同,我们必须显式定义@EnableWebMvc来设置默认的Spring MVC配置,而

@ComponentScan可以指定用于扫描组件的包。

@EnableWebMvc注解提供了Spring Web MVC配置,比如设置dispatcher servlet,启用@ controller和@RequestMapping注解以及设置其他默认值。

@ComponentScan配置组件扫描指令,指定要扫描的包。

<强>初始化类

接下来,我们需要添加一个实现WebApplicationInitializer接口的类:

public  class  AppInitializer  implements  WebApplicationInitializer  {   ,   @Override才能   public 才能;void  onStartup (ServletContext 容器),throws  ServletException  {   ,,,AnnotationConfigWebApplicationContext  context =, new  AnnotationConfigWebApplicationContext ();   ,,,context.scan (“com.qulingfeng");   ,,,container.addListener (new  ContextLoaderListener(上下文));   ,   ,,,ServletRegistration.Dynamic  dispatcher =,   ,,,,container.addServlet (“mvc",, new  DispatcherServlet(上下文));   ,,,dispatcher.setLoadOnStartup (1);   ,,,dispatcher.addMapping (“/?;,,   ,,}   }

在这里,我们使用AnnotationConfigWebApplicationContext类创建春上下文,这意味着我们仅使用基于注释的配置。然后,我们指定要扫描组件和配置类的包。

最后,我们定义网络应用程序的入口点——DispatcherServlet。

此类可以完全替换& lt;Servlet 3.0版本中网络的。xml文件。

<强> xml配置

让我们快速看一下等效的xml web配置:

& lt;上下文:component-scan 基础包=癱om.qulingfeng.controller",/比;   & lt; mvc: annotation-driven /祝辞

我们可以用上面的WebConfig类替换这个XML文件。
要启动应用程序,我们可以使用一个初始化器类来加载XML配置或网络。xml文件。

关于使用弹簧怎么创建一个网站应用问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注行业资讯频道了解更多相关知识。

使用弹簧怎么创建一个网站应用