单例+预加载(默认) //项目一启动就产生一个且仅一个实例,即单例。 //并且,通过 @Autowired 只能获得这个单例。new Test()则不受单例限制 @Component public class Test{ } 单例+懒加载 //项目启动时不加载 //仅当 TestDemo 类的 @Autowired Test 被扫描到时,才生成 Test 类的一个且仅一个实例。 //并且,通过 @Autowired 只能获得这个单例。new Test()则不受单例限制 @Lazy @Component public class Test{ } 正确的加载时机 package org.foo.service; import javax.annotation.PostConstruct; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class TestDemo { //禁止使用 @Autowired 标签加载 @Lazy 的类 // @Autowired // TestSingle testSingle; //通过 BeanFactory 接口创建实例 @Autowired BeanFactory beanFactory; public void doSth(){ //test 是 Test 类名首字母小写!一定要首字母小写! //只有运行到这里 Test 类才被实例化,延迟加载成功 TestSingle ts=(TestSingle) beanFactory.getBean("test"); } } 错误的加载时机: //懒加载无效 //项目启动时 TestDemo 被加载时,扫描 @Autowired 标签,生成 Test 的单例 @Component public class TestDemo{ @Autowired // 项目启动时,这里就会创建 Test 的单例,Test 类的懒加载无效 Test test; } 多例+懒加载(仅支持懒加载) //每个 @Autowired 生成一个实例,可以有多个实例 @Scope("prototype") //@Lazy //无论加不加 @Lazy,被 @Scope("prototype") 修饰的类都会 懒加载。 @Component public class Test{ }