package com.niewj.config;

import com.niewj.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;

@Configuration
public class ScopeConfig {

    /**
     * @return
     */
    @Scope("singleton")
    @Lazy
    @Bean
    public Person person() {
        return new Person("json", 22);
    }
}
  1. 单例bean 默认是预先 初始化的;
  2. prototype 默认是延迟初始化; 只有getBean才会初始化构造(调用构造方法)
  3. singleton单例的如果想延迟初始化, 可以在@Bean同时加注解@Lazy

    singleton的不管获取几次, 只初始化一次;
    prototype的获取几次, 初始化几次!

Bean的作用域: 完整的是:
singleton(默认)
prototype
request(Web)
session(Web)

后两种用的少


丰木
325 声望21 粉丝

遇见超乎想象的自己!