spring常見註解 ----Scope

@Scope的做用  調整組件的做用域java

package common.config;

import common.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
public class MainConfig2 {

    /*
     * @see ConfigurableBeanFactory#SCOPE_PROTOTYPE
     * @see ConfigurableBeanFactory#SCOPE_SINGLETON
     * @see org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST
     * @see org.springframework.web.context.WebApplicationContext#SCOPE_SESSION
     * prototype:多實例的
     * singleton:單實例的
     * request:同一次請求建立一個實例
     * session:同一個session建立一個實例
     */
    @Scope(value = "singleton")
    @Bean
    public Person person() {
        System.out.println("建立person");
        return new Person("lisi", 21);
    }
}
package common;

import common.bean.Person;
import common.config.MainConfig2;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MainTest {
    @Test
    public void test() {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig2.class);
        System.out.println("IOC容器建立完成");
        Person person = (Person) applicationContext.getBean("person");
        Person person1 = (Person) applicationContext.getBean("person");
        System.out.println(person == person1);
    }
}

運行測試代碼打印內容爲:web

能夠看出當scope的value爲singleton(默認值)時,IOC容器啓動時會調用方法建立對象放到IOC容器中,之後每次獲取都是從容器中直接獲取。所以單實例狀況下,不論何時獲取實例,都是同一個。spring

再次改成多實例session

package common.config;

import common.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
public class MainConfig2 {

    /*
     * @see ConfigurableBeanFactory#SCOPE_PROTOTYPE
     * @see ConfigurableBeanFactory#SCOPE_SINGLETON
     * @see org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST
     * @see org.springframework.web.context.WebApplicationContext#SCOPE_SESSION
     * prototype:多實例的
     * singleton:單實例的
     * request:同一次請求建立一個實例
     * session:同一個session建立一個實例
     */
    @Scope(value = "prototype")
    @Bean
    public Person person() {
        System.out.println("建立person");
        return new Person("lisi", 21);
    }
}

執行上述測試代碼,運行結果爲:app

scope的value爲prototype時,IOC容器啓動時並不會調用方法建立對象放在容器中。而是每次獲取的時候纔會調用方法建立對象。測試

相關文章
相關標籤/搜索