单例对象实例注入多例对象实例时,由于单例对象在容器中只有一次初始化的机会,所以单例对象始终注入的都是同一个对象,这样不能满足我们需要多例的要求。
解决办法:
1)手动new一个对象,这种方法可以确保每次对象都是新的,但是有个弊端就是没有用spring容器管理对象,spring不能帮我们注入需要的属性实例。
2)继承ApplicationContextAware接口,手动获取bean,例子如下:
1、现象描述
TestController想每次注入不同的TestService实例, 而TestService 是多例的
@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 {
}
2、解决办法: 实现 ApplicationContextAware/BeanFactoryAware 接口, 注入bean工厂, 每次从容器中获取对象
@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;
}
}
@Controller
public class TestController implements BeanFactoryAware{
// @Autowired
// private TestService testService;
private BeanFactory beanFactory;
@RequestMapping("/test")
@ResponseBody
public String test() {
TestService testService = beanFactory.getBean(TestService.class);
testService.test();
return testService.hashCode() + "";
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
//该方法是在spring容器初始化时调用,传入beanFactory
this.beanFactory = beanFactory;
}
}
https://blog.csdn.net/wrongyao/article/details/85158043
https://www.cnblogs.com/tflowingcloud/p/8443010.html
https://www.cnblogs.com/ssh-html/p/10403590.html