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

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)

后两种用的少

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理