@Scope设置组件作用域
import com.ken.domain.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
public class MainConfig {
/**
* singleton: 定义该bean是单例模式,ioc容器启动会调用方法创建对象放到ioc容器中,以后每次获取直接从容器中
* prototype:每次调用都会创建一个新的bean实列。ioc容器启动并不会创建实例,而是在每次获取的时候去创建对象
* request:同一次请求创建一个实例
* session:同一个session创建一个实例
* @return
*/
@Scope("prototype")
@Bean(value = "person")
public Person person() {
return new Person("lisi", 20);
}
}
@Lazy懒加载。针对于singleton,@Lazy使得,ioc容器启动的时候,不去创建bean,而是,在使用到bean的时候再创建。
import com.ken.domain.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
@Configuration
public class MainConfig {
@Lazy
@Bean(value = "person")
public Person person() {
System.out.println("chuangjain");
return new Person("lisi", 20);
}
}