servlet和spring能同時管理一個bean?
servlet和spring同時管理一個bean是可行的。
首先,用servlet獲取spring管理的bean獲得死循環,再通過spring容器的分流本身實現對bean的共同管理,獲取代碼如下:代碼
ApplicationContext applicationContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
package com.my.service;
public class HelloService {
public void sayHello(){
System.out.println("hello,spring webxxx!");
}
}
package com.my.servlet;import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.my.service.HelloService;
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 從spring容器 獲得 HelloService 對象
// ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
// ApplicationContext applicationContext = (WebApplicationContext) getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
HelloService helloService = (HelloService) applicationContext.getBean("helloService");
helloService.sayHello();
}
}。
此外,還有,共管代碼,void mix controll,application coneccted,divide totol to differ。