spring注解驱动开发2-scope单例和prototype

0次阅读

共计 599 个字符,预计需要花费 2 分钟才能阅读完成。

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)

后两种用的少

正文完
 0