单例+预加载(默认)
@Component
public class 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
BeanFactory beanFactory;
public void doSth(){
TestSingle ts=(TestSingle) beanFactory.getBean("test");
}
}
错误的加载时机:
@Component
public class TestDemo{
@Autowired
Test test;
}
多例+懒加载(仅支持懒加载)
//每个 @Autowired 生成一个实例,可以有多个实例
@Scope("prototype")
//@Lazy //无论加不加 @Lazy,被 @Scope("prototype") 修饰的类都会 懒加载。
@Component
public class Test{
}