Spring当中aop:scoped-proxy 的用法
4.
当把生命周期短的bean(比如下例中的MyBean)注入到生命周期长的bean(比如下例中的SingletonBean)时,我们必须做特殊处理,比如加
例 2.4.1
package com;
public class MyBean implements IMyBean{
private int count;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public void increment()
{
count ++;
}
}
package com;
public interface IMyBean {
public void increment();
public int getCount();
}
package com;
public class SingletonBean {
private MyBean myBean;
public int getCount() {
return myBean.getCount();
}
public void increment() {
myBean.increment();
}
public void setMyBean(MyBean myBean) {
this.myBean = myBean;
}
}
package com;
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContextUtils;
import service.interfac.ILoginService;
@Controller
public class HelloWorldController {
private ILoginService loginServic;
private IMyBean myBean;
@RequestMapping("/helloa")
public ModelAndView helloWorld(HttpServletRequest request, HttpServletResponse response,
HttpSession sesssion) {
ServletContext sc=RequestContextUtils.getWebApplicationContext(request).getServletContext();
WebApplicationContext wac=WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
ILoginService loginServic=(ILoginService)wac.getBean("loginService");
SingletonBean singletonBean=(SingletonBean)wac.getBean("singletonBean");
// loginServic.login();
singletonBean.increment();
System.out.println("myBean.getCount() "+singletonBean.getCount());
System.out.println("after loginServic.login()");
return new ModelAndView("/helloq", "message", "你好");
}
}
输出结果:(在同一个浏览器中反复执行就是以下结果,换一个浏览器数据重新向上加)
myBean.getCount() 1
after loginServic.login()
myBean.getCount() 2
after loginServic.login()
myBean.getCount() 3
after loginServic.login()
更多内容请见原文,原文转载自:https://blog.csdn.net/qq_44591615/article/details/109206505