@Scope @Lazy @Bean注解注解
  IsgRbvMUyxpD 2023年11月02日 61 0


先看下面代码:

package com.xhx.spring.config;

import com.xhx.spring.domain.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;

import java.beans.PersistenceDelegate;

@Configuration
public class ScopeConfig {

@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) //单例 多例
@Bean
@Lazy //是否在用到的时候再初始化
public Person getPerson(){
System.out.println("初始化。。");
return new Person("xu",25);
}

// @Autowired
// private Person person1;
@Autowired
@Lazy //是否在用到的时候再注入
private Person person2;
}

@Bean:  Indicates that a method produces a bean to be managed by the Spring container.  把一个方法产生的bean交给spring管理。可以用name属性指定注入的名称

@Scope:表明是单例还是多例注入,有两个值:

public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {

/**
* Scope identifier for the standard singleton scope: "singleton".
* Custom scopes can be added via {@code registerScope}.
* @see #registerScope
*/
String SCOPE_SINGLETON = "singleton";

/**
* Scope identifier for the standard prototype scope: "prototype".
* Custom scopes can be added via {@code registerScope}.
* @see #registerScope
*/
String SCOPE_PROTOTYPE = "prototype";

....
}

@Lazy:表示用到的时候初始化,用到的时候再进行注入

 

测试类:

package com.xhx.spring;

import com.xhx.spring.config.ScopeConfig;
import com.xhx.spring.domain.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Arrays;

@RunWith(SpringRunner.class)
@SpringBootTest
public class Spring5ScopeLazyApplicationTests {

@Test
public void testScope() {
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(ScopeConfig.class);
Person bean = annotationConfigApplicationContext.getBean(Person.class);
System.out.println(bean);
Person bean2 = annotationConfigApplicationContext.getBean(Person.class);
System.out.println(bean2);

}

}

**实时内容请关注微信公众号,公众号与博客同时更新:程序员星星**

@Scope @Lazy @Bean注解注解_@Scope

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  ltERVYe6WHLK   2023年11月02日   21   0   0 数据类型C#初始化
IsgRbvMUyxpD
最新推荐 更多