springboot自定义servlet和servlet中的@Autowired问题

xiaoxiao2021-02-28  40

今天的需求是外部系统post本系统url,本系统对request进行解析,再response。

系统框架是spring cloud。决定用servlet来过滤post请求。

spring boot 可以直接在入口类里增加@ServletComponentScan这个注解来实现启动时的servlet加载,如果入口类和自定义servlet类不在同一个包下,需要指定加载时扫描的包路径:@ServletComponentScan(basePackages = "com.*.*.servlet")

@ServletComponentScan(basePackages = "com.test.servlet") public class AppConfig {}

然后需要在自定义servlet类里加上@WebServlet(urlPatterns = "/test")注解,urlPatterns设置为相对路径。这样配置之后的post全路径为http://localhost:8080/test

@WebServlet(urlPatterns = "/test") public class TestServlet extends HttpServlet {}

servlet类是由servlet容器管理,而不是spring容器,所以如果想在自定义servlet类中使用@Autowired来自动注入类,单纯这样是不行的。需要重写init()方法,在servlet初始化时给它充填带注解的bean实例。

public void init() throws ServletException { super.init(); //获取autowire的bean WebApplicationContextUtils.getWebApplicationContext(getServletContext()).getAutowireCapableBeanFactory() .autowireBean(this); }

转载请注明原文地址: https://www.6miu.com/read-2614373.html

最新回复(0)