我正在尝试注册自定义servlet。
我在@Configuration
类中使用了此代码:
@Bean (name="probe")
public PingServlet probe(){
return new PingServlet();
}
我认为这会被映射到/ probe,但它并没有。我映射到' /'原因是在课程ServletContextInitializerBeans
中有这种方法:
private <T, B extends T> void addAsRegistrationBean(ListableBeanFactory beanFactory,
Class<T> type, Class<B> beanType, RegistrationBeanAdapter<T> adapter) {
List<Map.Entry<String, B>> beans = getOrderedBeansOfType(beanFactory, beanType,
this.seen);
for (Entry<String, B> bean : beans) {
if (this.seen.add(bean.getValue())) {
int order = getOrder(bean.getValue());
String beanName = bean.getKey();
// One that we haven't already seen
RegistrationBean registration = adapter.createRegistrationBean(beanName,
bean.getValue(), beans.size());
registration.setName(beanName);
registration.setOrder(order);
this.initializers.add(type, registration);
if (this.log.isDebugEnabled()) {
this.log.debug(
"Created " + type.getSimpleName() + " initializer for bean '"
+ beanName + "'; order=" + order + ", resource="
+ getResourceDescription(beanName, beanFactory));
}
}
}
}
行List<Map.Entry<String, B>> beans = getOrderedBeansOfType(beanFactory, beanType, this.seen);
,仅返回1个bean的列表(我的servlet),虽然beanType是javax Servlet,我希望DispatcherServlet也在那里(我也使用Spring MVC)。
这导致以下方法出错(在ServletRegistrationBeanAdapter
类中):
@Override
public RegistrationBean createRegistrationBean(String name, Servlet source,
int totalNumberOfSourceBeans) {
String url = (totalNumberOfSourceBeans == 1 ? "/" : "/" + name + "/");
if (name.equals(DISPATCHER_SERVLET_NAME)) {
url = "/"; // always map the main dispatcherServlet to "/"
}
ServletRegistrationBean bean = new ServletRegistrationBean(source, url);
bean.setMultipartConfig(this.multipartConfig);
return bean;
}
由于bean列表的大小为1,因此在createRegistrationBean中硬编码映射到&#39; /&#39;。
这反过来导致他们嵌入式码头失败,因为有2个映射到&#39; /&#39; (DispatcherServlet和我的PingServlet)。
任何想法在这里出了什么问题?
答案 0 :(得分:0)
感谢@M。 Deinum这有效:
@Bean
public ServletRegistrationBean pingRegistration(PingServlet pingServlet) {
ServletRegistrationBean registration = new ServletRegistrationBean(
pingServlet);
registration.addUrlMappings("/probe/*");
return registration;
}