Spring 环境 5.0.x ,JDK 8
Bean的作用域
常用的singleton或prototype,其他的都依赖于web环境,这里就先不说明了。下面是spring官网对单例和原型的解释。
众所周知,在Spring容器中,bean的scope默认是singleton单例的。
如果在singleton的bean中依赖了prototype的bean,那么会出现下面的问题,原型的bean每次获取的都是同一个对象。
package com.along.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
/**
* scope默认是singleton
*/
@Repository
public class OrderDao {
@Autowired
private IndexDao indexDao;
//这里分别打印当前orderDao的hashCode和它所依赖indexDao的hashCode
public void order(){
System.out.println("orderDao:"+this.hashCode());
System.out.println("indexDao:"+indexDao.hashCode());
}
}
package com.along.dao;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
@Repository
@Scope("prototype")
public class IndexDao {
public void test(){
System.out.println("IndexDao#test()");
}
}
package com.along.config;
import o