问题:如标题所说,程序中有一个Entity的类,使用了@Component 和 @Scope("prototype") 注解。Entity这种类对应的是数据库的表,定是要多例。但在spring-mvc启动的时候,实现无参构造函数,断点发现只调用了两次就不再调用。PS(在该Entity类上用了多少个@Autowired就调用了多少次)。多次调用Controller中方法后,entity居然注入为null。
解决方法:1.Entity 和 使用的Autowired注入的两个类都是用@Scope("prototype") 进行注解,比如我的Controller类中有,那么Controller类也得用@Scope("prototype"),每次请求也得重新创建Controller。Entity也就重新创建。
2.Spring建议Controller使用单利,这样有助于提高性能。方法1虽能解决,但我建议使用动态直接获取方法。即使用WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
wac.getBean("xxxx");
敬上错别字,收下!