单例对象实例注入多例对象实例时,由于单例对象在容器中只有一次初始化的机会,所以单例对象始终注入的都是同一个对象,这样不能满足我们需要多例的要求。
解决办法:
1)手动new一个对象,这种方法可以确保每次对象都是新的,但是有个弊端就是没有用spring容器管理对象,spring不能帮我们注入需要的属性实例。
2)继承ApplicationContextAware接口,手动获取bean,例子如下:
1、现象描述
TestController想每次注入不同的TestService实例,TestService注入了TestService2
TestController代码如下
@Controller
public class TestController {
@Autowired
private TestService testService;
@RequestMapping("/test")
@ResponseBody
public String test() {
testService.test();
return testService.hashCode() + "";
}
}
TestService代码如下,通过@Scope("prototype")申明注入多例对象
@Service
@Scope("prototype")
public class TestService {
@Autowired
private TestService2 testService2;
public void test(){
testService2.test();
}
}
TestService2代码如下,主要模拟TestService需要注入的业务类。
@Service
public class TestService2 {
public void test() {
System.out.println("test------------");
}
}
结果:每次的hashcode都是一样的
2、解决办法
如果不用spring容器,可以直接new一个TestService对象,但是这样做,就需要再new一个TestService2,如果依赖很多显然是不合理的。所以这边介绍Spring Aware的方法
Controller代码修改如下
@Controller
public class TestController implements ApplicationContextAware {
// @Autowired
// private TestService testService;
private ApplicationContext applicationContext;
@RequestMapping("/test")
@ResponseBody
public String test() {
TestService testService = applicationContext.getBean(TestService.class);
testService.test();
return testService.hashCode() + "";
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
结果:每次的hashcode都是不一样的
当Spring的单例对象需要注入多例对象时,每次请求会得到相同的实例,不符合需求。本文介绍如何通过实现ApplicationContextAware接口,手动从Spring容器获取多例对象,确保每次请求都能获得新的实例。
3102

被折叠的 条评论
为什么被折叠?



