@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容器启动时并不会调用方法建立对象放在容器中。而是每次获取的时候才会调用方法建立对象。测试