如何使用@Scope设置组件作用域
1、在组件配置类中声明一个bean类,默认情况下是单实例的。
package com.gwolf.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.gwolf.vo.Person;
@Configuration
public class ComponentConfig {
@Bean("person")
public Person getPerson() {
return new Person("百度", 10000);
}
}
2、在测试类中判断从容器中取得的java对象是不是同一个。
package com.gwolf.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.gwolf.config.ComponentConfig;
public class ComponentTest {
public static void main(String[] args) {
ApplicationContext applicationContext =
new AnnotationConfigApplicationContext(ComponentConfig.class);
String[] beanNames = applicationContext.getBeanDefinitionNames();
for(String bean : beanNames) {
System.out.println(bean);
}
Object bean1 = applicationContext.getBean("person");
Object bean2 = applicationContext.getBean("person");
System.out.println(bean1 == bean2);
}
}
3、@Scope注解的值有四个:
@see ConfigurableBeanFactory#SCOPE_PROTOTYPE 表示多实例
* @see ConfigurableBeanFactory#SCOPE_SINGLETON 表示单实例
* @see org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST 这个只有在web开发环境中才能使用,同一个请求创建一个实例
* @see org.springframework.web.context.WebApplicationContext#SCOPE_SESSION 这个只有在web开发环境中才能使用,同一个session创建一个实例。
4、现在把组件配置中返回的对象设置为多实例:
package com.gwolf.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import com.gwolf.vo.Person;
@Configuration
public class ComponentConfig {
@Bean("person")
@Scope("prototype")
public Person getPerson() {
return new Person("百度", 10000);
}
}
5、在测试类中判断从容器中取得的java对象是不是同一个:现在程序应该会返回false。
6、在单实例的情况下,spring容器启动会调用方法创建对象放到容器中,以后每次获取就是直接从容器中拿。
在多实例的情况下,在获取bean的情况下才会创建bean对象。