如何将带有 init-params 的 web.xml 移动到 Java 配置?
我使用的是 Spring boot 2.6.3,我的项目中有以下 web.xml
。将其转移到 Java 配置的理想方法是什么?
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name>My Web Application</display-name>
<servlet>
<servlet-name>my</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.xyz.my.service.custom.config.CustomServiceConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>my</servlet-name>
<url-pattern>/v1/</url-pattern>
</servlet-mapping>
</web-app>
I am using Spring boot 2.6.3 and I have the following web.xml
in my project. What would be the ideal way to move this to Java config?
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name>My Web Application</display-name>
<servlet>
<servlet-name>my</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.xyz.my.service.custom.config.CustomServiceConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>my</servlet-name>
<url-pattern>/v1/</url-pattern>
</servlet-mapping>
</web-app>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你不需要所有这些。只需放弃您的
web.xml
即可。AnnotationConfigWebApplicationContext
(实际上 Spring Boot 有一个专门的子类)是默认的,如果您的
@SpringBootApplication
注解的类是在com.xyz.my.service
中,您不需要执行任何操作。将自动检测您的CustomServiceConfig
。如果不是,您可以将@Import(CustomServiceConfig.class)
添加到您的@SpringBootApplication
带注释的类。You don't need all of that. Just ditch your
web.xml
. TheAnnotationConfigWebApplicationContext
(actually Spring Boot has a specialized sub-class for it) is the default and your configuration class just can be imported or automatically detectedIf your
@SpringBootApplication
annotated class is in thecom.xyz.my.service
you don't need to do anything. YourCustomServiceConfig
will be automatically detected. If it isn't you can add an@Import(CustomServiceConfig.class)
to your@SpringBootApplication
annotated class.