如何使用@Scope设置组件作用域

2025-04-27 18:51:19

1、在组件配置类中声明一个bean类,默认情况下是单实例的。package com.gwolf.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import com.gwolf.vo.Person;@Configurationpublic class ComponentConfig { @Bean("person") public Person getPerson() { return new Person("百度", 10000); }}

如何使用@Scope设置组件作用域

2、在测试类中判断从容器中取得的java对象是不是同一个。package com.gwolf.test;import org.spr足毂忍珩ingframework.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); }}

如何使用@Scope设置组件作用域

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创建一个实例。

如何使用@Scope设置组件作用域

4、现在把组件配置中返回的对象设置为多实例:package com.gwolf.config;import org.springframework.context.annotatio荏鱿胫协n.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Scope;import com.gwolf.vo.Person;@Configurationpublic class ComponentConfig { @Bean("person") @Scope("prototype") public Person getPerson() { return new Person("百度", 10000); }}

如何使用@Scope设置组件作用域

5、在测试类中判断从容器中取得的java对象是不是同一个:现在程序应该会返回false。

如何使用@Scope设置组件作用域

6、在单实例的情况下,spring容器启动会调用方法创建对象放到容器中,以后每次获取就是直接从容器中拿。在多实例的情况下,在获取bean的情况下才会创建bean对象。

如何使用@Scope设置组件作用域
如何使用@Scope设置组件作用域
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢