org.springframework.beans.factory.ObjectFactory Java Examples

The following examples show how to use org.springframework.beans.factory.ObjectFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ObjectFactoryCreatingFactoryBeanTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testDoesNotComplainWhenTargetBeanNameRefersToSingleton() throws Exception {
	final String targetBeanName = "singleton";
	final String expectedSingleton = "Alicia Keys";

	BeanFactory beanFactory = mock(BeanFactory.class);
	given(beanFactory.getBean(targetBeanName)).willReturn(expectedSingleton);

	ObjectFactoryCreatingFactoryBean factory = new ObjectFactoryCreatingFactoryBean();
	factory.setTargetBeanName(targetBeanName);
	factory.setBeanFactory(beanFactory);
	factory.afterPropertiesSet();
	ObjectFactory<?> objectFactory = factory.getObject();
	Object actualSingleton = objectFactory.getObject();
	assertSame(expectedSingleton, actualSingleton);
}
 
Example #2
Source File: WebApplicationContextUtils.java    From java-technology-stack with MIT License 6 votes vote down vote up
public static void registerFacesDependencies(ConfigurableListableBeanFactory beanFactory) {
	beanFactory.registerResolvableDependency(FacesContext.class, new ObjectFactory<FacesContext>() {
		@Override
		public FacesContext getObject() {
			return FacesContext.getCurrentInstance();
		}
		@Override
		public String toString() {
			return "Current JSF FacesContext";
		}
	});
	beanFactory.registerResolvableDependency(ExternalContext.class, new ObjectFactory<ExternalContext>() {
		@Override
		public ExternalContext getObject() {
			return FacesContext.getCurrentInstance().getExternalContext();
		}
		@Override
		public String toString() {
			return "Current JSF ExternalContext";
		}
	});
}
 
Example #3
Source File: SimpSessionScope.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
	SimpAttributes simpAttributes = SimpAttributesContextHolder.currentAttributes();
	Object scopedObject = simpAttributes.getAttribute(name);
	if (scopedObject != null) {
		return scopedObject;
	}
	synchronized (simpAttributes.getSessionMutex()) {
		scopedObject = simpAttributes.getAttribute(name);
		if (scopedObject == null) {
			scopedObject = objectFactory.getObject();
			simpAttributes.setAttribute(name, scopedObject);
		}
		return scopedObject;
	}
}
 
Example #4
Source File: AbstractRequestAttributesScope.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
	RequestAttributes attributes = RequestContextHolder.currentRequestAttributes();
	Object scopedObject = attributes.getAttribute(name, getScope());
	if (scopedObject == null) {
		scopedObject = objectFactory.getObject();
		attributes.setAttribute(name, scopedObject, getScope());
		// Retrieve object again, registering it for implicit session attribute updates.
		// As a bonus, we also allow for potential decoration at the getAttribute level.
		Object retrievedObject = attributes.getAttribute(name, getScope());
		if (retrievedObject != null) {
			// Only proceed with retrieved object if still present (the expected case).
			// If it disappeared concurrently, we return our locally created instance.
			scopedObject = retrievedObject;
		}
	}
	return scopedObject;
}
 
Example #5
Source File: ScopingTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
	if (createNewScope) {
		beans.clear();
		// reset the flag back
		createNewScope = false;
	}

	Object bean = beans.get(name);
	// if a new object is requested or none exists under the current
	// name, create one
	if (bean == null) {
		beans.put(name, objectFactory.getObject());
	}

	return beans.get(name);
}
 
Example #6
Source File: DefaultSingletonBeanRegistry.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Return the (raw) singleton object registered under the given name.
 * <p>Checks already instantiated singletons and also allows for an early
 * reference to a currently created singleton (resolving a circular reference).
 * @param beanName the name of the bean to look for
 * @param allowEarlyReference whether early references should be created or not
 * @return the registered singleton object, or {@code null} if none found
 */
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
	Object singletonObject = this.singletonObjects.get(beanName);
	if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
		synchronized (this.singletonObjects) {
			singletonObject = this.earlySingletonObjects.get(beanName);
			if (singletonObject == null && allowEarlyReference) {
				ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
				if (singletonFactory != null) {
					singletonObject = singletonFactory.getObject();
					this.earlySingletonObjects.put(beanName, singletonObject);
					this.singletonFactories.remove(beanName);
				}
			}
		}
	}
	return singletonObject;
}
 
Example #7
Source File: ScopingTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
	if (createNewScope) {
		beans.clear();
		// reset the flag back
		createNewScope = false;
	}

	Object bean = beans.get(name);
	// if a new object is requested or none exists under the current
	// name, create one
	if (bean == null) {
		beans.put(name, objectFactory.getObject());
	}

	return beans.get(name);
}
 
Example #8
Source File: AbstractRequestAttributesScope.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
	RequestAttributes attributes = RequestContextHolder.currentRequestAttributes();
	Object scopedObject = attributes.getAttribute(name, getScope());
	if (scopedObject == null) {
		scopedObject = objectFactory.getObject();
		attributes.setAttribute(name, scopedObject, getScope());
		// Retrieve object again, registering it for implicit session attribute updates.
		// As a bonus, we also allow for potential decoration at the getAttribute level.
		Object retrievedObject = attributes.getAttribute(name, getScope());
		if (retrievedObject != null) {
			// Only proceed with retrieved object if still present (the expected case).
			// If it disappeared concurrently, we return our locally created instance.
			scopedObject = retrievedObject;
		}
	}
	return scopedObject;
}
 
Example #9
Source File: DefaultSingletonBeanRegistry.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Return the (raw) singleton object registered under the given name.
 * <p>Checks already instantiated singletons and also allows for an early
 * reference to a currently created singleton (resolving a circular reference).
 * @param beanName the name of the bean to look for
 * @param allowEarlyReference whether early references should be created or not
 * @return the registered singleton object, or {@code null} if none found
 */
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
	Object singletonObject = this.singletonObjects.get(beanName);
	// 检查缓存中是否存在实例
	if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
		// 记住,公共变量都需要加锁操作,避免多线程并发修改
		synchronized (this.singletonObjects) {
			// 如果此 bean 正在加载则不处理
			singletonObject = this.earlySingletonObjects.get(beanName);
			if (singletonObject == null && allowEarlyReference) {
				// 当某些方法需要提前初始化,调用 addSingletonFactory 方法将对应的
				// objectFactory 初始化策略存储在 earlySingletonObjects,并且从 singletonFactories 移除
				ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
				if (singletonFactory != null) {
					singletonObject = singletonFactory.getObject();
					this.earlySingletonObjects.put(beanName, singletonObject);
					this.singletonFactories.remove(beanName);
				}
			}
		}
	}
	return singletonObject;
}
 
Example #10
Source File: DefaultListableBeanFactory.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
@Nullable
public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
		@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

	descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
	if (Optional.class == descriptor.getDependencyType()) {
		return createOptionalDependency(descriptor, requestingBeanName);
	}
	else if (ObjectFactory.class == descriptor.getDependencyType() ||
			ObjectProvider.class == descriptor.getDependencyType()) {
		return new DependencyObjectProvider(descriptor, requestingBeanName);
	}
	else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
		return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName);
	}
	else {
		Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
				descriptor, requestingBeanName);
		if (result == null) {
			result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
		}
		return result;
	}
}
 
Example #11
Source File: OpenApiResource.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Instantiates a new Open api resource.
 *
 * @param openAPIBuilderObjectFactory the open api builder object factory
 * @param requestBuilder the request builder
 * @param responseBuilder the response builder
 * @param operationParser the operation parser
 * @param requestMappingHandlerMapping the request mapping handler mapping
 * @param actuatorProvider the actuator provider
 * @param operationCustomizers the operation customizers
 * @param openApiCustomisers the open api customisers
 * @param springDocConfigProperties the spring doc config properties
 * @param springSecurityOAuth2Provider the spring security o auth 2 provider
 * @param routerFunctionProvider the router function provider
 * @param repositoryRestResourceProvider the repository rest resource provider
 */
@Autowired
public OpenApiResource(ObjectFactory<OpenAPIBuilder> openAPIBuilderObjectFactory, AbstractRequestBuilder requestBuilder,
		GenericResponseBuilder responseBuilder, OperationBuilder operationParser,
		RequestMappingInfoHandlerMapping requestMappingHandlerMapping,
		Optional<ActuatorProvider> actuatorProvider,
		Optional<List<OperationCustomizer>> operationCustomizers,
		Optional<List<OpenApiCustomiser>> openApiCustomisers,
		SpringDocConfigProperties springDocConfigProperties,
		Optional<SecurityOAuth2Provider> springSecurityOAuth2Provider,
		Optional<RouterFunctionProvider> routerFunctionProvider,
		Optional<RepositoryRestResourceProvider> repositoryRestResourceProvider) {
	super(DEFAULT_GROUP_NAME, openAPIBuilderObjectFactory, requestBuilder, responseBuilder, operationParser, operationCustomizers, openApiCustomisers, springDocConfigProperties,actuatorProvider);
	this.requestMappingHandlerMapping = requestMappingHandlerMapping;
	this.springSecurityOAuth2Provider = springSecurityOAuth2Provider;
	this.routerFunctionProvider = routerFunctionProvider;
	this.repositoryRestResourceProvider = repositoryRestResourceProvider;
}
 
Example #12
Source File: MultipleOpenApiResource.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Instantiates a new Multiple open api resource.
 *
 * @param groupedOpenApis the grouped open apis
 * @param defaultOpenAPIBuilder the default open api builder
 * @param requestBuilder the request builder
 * @param responseBuilder the response builder
 * @param operationParser the operation parser
 * @param requestMappingHandlerMapping the request mapping handler mapping
 * @param actuatorProvider the actuator provider
 * @param springDocConfigProperties the spring doc config properties
 * @param springSecurityOAuth2Provider the spring security o auth 2 provider
 * @param routerFunctionProvider the router function provider
 * @param repositoryRestResourceProvider the repository rest resource provider
 */
public MultipleOpenApiResource(List<GroupedOpenApi> groupedOpenApis,
		ObjectFactory<OpenAPIBuilder> defaultOpenAPIBuilder, AbstractRequestBuilder requestBuilder,
		GenericResponseBuilder responseBuilder, OperationBuilder operationParser,
		RequestMappingInfoHandlerMapping requestMappingHandlerMapping, Optional<ActuatorProvider> actuatorProvider,
		SpringDocConfigProperties springDocConfigProperties, Optional<SecurityOAuth2Provider> springSecurityOAuth2Provider,
		Optional<RouterFunctionProvider> routerFunctionProvider,
		Optional<RepositoryRestResourceProvider> repositoryRestResourceProvider) {

	this.groupedOpenApis = groupedOpenApis;
	this.defaultOpenAPIBuilder = defaultOpenAPIBuilder;
	this.requestBuilder = requestBuilder;
	this.responseBuilder = responseBuilder;
	this.operationParser = operationParser;
	this.requestMappingHandlerMapping = requestMappingHandlerMapping;
	this.actuatorProvider = actuatorProvider;
	this.springDocConfigProperties = springDocConfigProperties;
	this.springSecurityOAuth2Provider = springSecurityOAuth2Provider;
	this.routerFunctionProvider = routerFunctionProvider;
	this.repositoryRestResourceProvider=repositoryRestResourceProvider;
}
 
Example #13
Source File: MultipleOpenApiSupportConfiguration.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Multiple open api resource multiple open api resource.
 *
 * @param groupedOpenApis the grouped open apis 
 * @param defaultOpenAPIBuilder the default open api builder 
 * @param requestBuilder the request builder 
 * @param responseBuilder the response builder 
 * @param operationParser the operation parser 
 * @param requestMappingHandlerMapping the request mapping handler mapping 
 * @param actuatorProvider the actuator provider 
 * @param springDocConfigProperties the spring doc config properties 
 * @param springSecurityOAuth2Provider the spring security o auth 2 provider 
 * @param routerFunctionProvider the router function provider 
 * @param repositoryRestResourceProvider the repository rest resource provider 
 * @return the multiple open api resource
 */
@Bean
@ConditionalOnMissingBean
@Lazy(false)
MultipleOpenApiResource multipleOpenApiResource(List<GroupedOpenApi> groupedOpenApis,
		ObjectFactory<OpenAPIBuilder> defaultOpenAPIBuilder, AbstractRequestBuilder requestBuilder,
		GenericResponseBuilder responseBuilder, OperationBuilder operationParser,
		RequestMappingInfoHandlerMapping requestMappingHandlerMapping,
		Optional<ActuatorProvider> actuatorProvider,
		SpringDocConfigProperties springDocConfigProperties,
		Optional<SecurityOAuth2Provider> springSecurityOAuth2Provider,
		Optional<RouterFunctionProvider> routerFunctionProvider,
		Optional<RepositoryRestResourceProvider> repositoryRestResourceProvider) {
	return new MultipleOpenApiResource(groupedOpenApis,
			defaultOpenAPIBuilder, requestBuilder,
			responseBuilder, operationParser,
			requestMappingHandlerMapping, actuatorProvider,
			springDocConfigProperties,
			springSecurityOAuth2Provider,
			routerFunctionProvider,repositoryRestResourceProvider);
}
 
Example #14
Source File: SpringDocWebMvcConfiguration.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Open api resource open api resource.
 *
 * @param openAPIBuilderObjectFactory the open api builder object factory
 * @param requestBuilder the request builder
 * @param responseBuilder the response builder
 * @param operationParser the operation parser
 * @param requestMappingHandlerMapping the request mapping handler mapping
 * @param actuatorProvider the actuator provider
 * @param springDocConfigProperties the spring doc config properties
 * @param operationCustomizers the operation customizers
 * @param openApiCustomisers the open api customisers
 * @param springSecurityOAuth2Provider the spring security o auth 2 provider
 * @param routerFunctionProvider the router function provider
 * @param repositoryRestResourceProvider the repository rest resource provider
 * @return the open api resource
 */
@Bean
@ConditionalOnMissingBean
@Lazy(false)
OpenApiResource openApiResource(ObjectFactory<OpenAPIBuilder> openAPIBuilderObjectFactory, AbstractRequestBuilder requestBuilder,
		GenericResponseBuilder responseBuilder, OperationBuilder operationParser,
		RequestMappingInfoHandlerMapping requestMappingHandlerMapping,
		Optional<ActuatorProvider> actuatorProvider,
		SpringDocConfigProperties springDocConfigProperties,
		Optional<List<OperationCustomizer>> operationCustomizers,
		Optional<List<OpenApiCustomiser>> openApiCustomisers,
		Optional<SecurityOAuth2Provider> springSecurityOAuth2Provider,
		Optional<RouterFunctionProvider> routerFunctionProvider,
		Optional<RepositoryRestResourceProvider> repositoryRestResourceProvider) {
	return new OpenApiResource(openAPIBuilderObjectFactory, requestBuilder,
			responseBuilder, operationParser,
			requestMappingHandlerMapping, actuatorProvider, operationCustomizers,
			openApiCustomisers, springDocConfigProperties, springSecurityOAuth2Provider,
			routerFunctionProvider, repositoryRestResourceProvider);
}
 
Example #15
Source File: ObjectFactoryCreatingFactoryBeanTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testDoesNotComplainWhenTargetBeanNameRefersToSingleton() throws Exception {
	final String targetBeanName = "singleton";
	final String expectedSingleton = "Alicia Keys";

	BeanFactory beanFactory = mock(BeanFactory.class);
	given(beanFactory.getBean(targetBeanName)).willReturn(expectedSingleton);

	ObjectFactoryCreatingFactoryBean factory = new ObjectFactoryCreatingFactoryBean();
	factory.setTargetBeanName(targetBeanName);
	factory.setBeanFactory(beanFactory);
	factory.afterPropertiesSet();
	ObjectFactory<?> objectFactory = factory.getObject();
	Object actualSingleton = objectFactory.getObject();
	assertSame(expectedSingleton, actualSingleton);
}
 
Example #16
Source File: WebApplicationContextUtils.java    From spring-analysis-note with MIT License 6 votes vote down vote up
public static void registerFacesDependencies(ConfigurableListableBeanFactory beanFactory) {
	beanFactory.registerResolvableDependency(FacesContext.class, new ObjectFactory<FacesContext>() {
		@Override
		public FacesContext getObject() {
			return FacesContext.getCurrentInstance();
		}
		@Override
		public String toString() {
			return "Current JSF FacesContext";
		}
	});
	beanFactory.registerResolvableDependency(ExternalContext.class, new ObjectFactory<ExternalContext>() {
		@Override
		public ExternalContext getObject() {
			return FacesContext.getCurrentInstance().getExternalContext();
		}
		@Override
		public String toString() {
			return "Current JSF ExternalContext";
		}
	});
}
 
Example #17
Source File: DefaultListableBeanFactory.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void registerResolvableDependency(Class<?> dependencyType, @Nullable Object autowiredValue) {
	Assert.notNull(dependencyType, "Dependency type must not be null");
	if (autowiredValue != null) {
		if (!(autowiredValue instanceof ObjectFactory || dependencyType.isInstance(autowiredValue))) {
			throw new IllegalArgumentException("Value [" + autowiredValue +
					"] does not implement specified dependency type [" + dependencyType.getName() + "]");
		}
		this.resolvableDependencies.put(dependencyType, autowiredValue);
	}
}
 
Example #18
Source File: FeignConfig.java    From XS2A-Sandbox with Apache License 2.0 5 votes vote down vote up
@Bean
public Decoder feignDecoder() {
	ObjectMapper objectMapper = new ObjectMapper();
	objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
	objectMapper.registerModule(new JavaTimeModule());
	HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter(objectMapper);
	ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(jacksonConverter);
	return new ResponseEntityDecoder(new SpringDecoder(objectFactory));
}
 
Example #19
Source File: SimpleScopeTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Before
public void setUp() {
	beanFactory = new DefaultListableBeanFactory();
	Scope scope = new NoOpScope() {
		private int index;
		private List<TestBean> objects = new LinkedList<>(); {
			objects.add(new TestBean());
			objects.add(new TestBean());
		}
		@Override
		public Object get(String name, ObjectFactory<?> objectFactory) {
			if (index >= objects.size()) {
				index = 0;
			}
			return objects.get(index++);
		}
	};

	beanFactory.registerScope("myScope", scope);

	String[] scopeNames = beanFactory.getRegisteredScopeNames();
	assertEquals(1, scopeNames.length);
	assertEquals("myScope", scopeNames[0]);
	assertSame(scope, beanFactory.getRegisteredScope("myScope"));

	XmlBeanDefinitionReader xbdr = new XmlBeanDefinitionReader(beanFactory);
	xbdr.loadBeanDefinitions(CONTEXT);
}
 
Example #20
Source File: ObjectFactoryLazyLookupDemo.java    From geekbang-lessons with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    // 注册 Configuration Class
    context.register(ObjectFactoryLazyLookupDemo.class);

    // 启动 Spring 应用上下文
    context.refresh();

    ObjectFactoryLazyLookupDemo objectFactoryLazyLookupDemo = context.getBean(ObjectFactoryLazyLookupDemo.class);

    // userObjectFactory userObjectProvider;

    // 代理对象
    ObjectFactory<User> userObjectFactory = objectFactoryLazyLookupDemo.userObjectFactory;
    ObjectFactory<User> userObjectProvider = objectFactoryLazyLookupDemo.userObjectProvider;

    System.out.println("userObjectFactory == userObjectProvider : " +
            (userObjectFactory == userObjectProvider));

    System.out.println("userObjectFactory.getClass() == userObjectProvider.getClass() : " +
            (userObjectFactory.getClass() == userObjectProvider.getClass()));

    // 实际对象(延迟查找)
    System.out.println("user = " + userObjectFactory.getObject());
    System.out.println("user = " + userObjectProvider.getObject());
    System.out.println("user = " + context.getBean(User.class));


    // 关闭 Spring 应用上下文
    context.close();
}
 
Example #21
Source File: DefaultSingletonBeanRegistry.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Add the given singleton factory for building the specified singleton
 * if necessary.
 * <p>To be called for eager registration of singletons, e.g. to be able to
 * resolve circular references.
 * @param beanName the name of the bean
 * @param singletonFactory the factory for the singleton object
 */
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
	Assert.notNull(singletonFactory, "Singleton factory must not be null");
	synchronized (this.singletonObjects) {
		if (!this.singletonObjects.containsKey(beanName)) {
			this.singletonFactories.put(beanName, singletonFactory);
			this.earlySingletonObjects.remove(beanName);
			this.registeredSingletons.add(beanName);
		}
	}
}
 
Example #22
Source File: SpringDocApp94Test.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
@Bean(name = "openApiResource")
public OpenApiResource openApiResource(ObjectFactory<OpenAPIBuilder> openAPIBuilderObjectFactory, AbstractRequestBuilder requestBuilder, GenericResponseBuilder responseBuilder,
		OperationBuilder operationParser,Optional<List<OperationCustomizer>> operationCustomizers,
		@Qualifier("defaultTestHandlerMapping") RequestMappingHandlerMapping requestMappingHandlerMapping,
		Optional<ActuatorProvider> actuatorProvider, SpringDocConfigProperties springDocConfigProperties,
		Optional<List<OpenApiCustomiser>> openApiCustomisers, Optional<SecurityOAuth2Provider> springSecurityOAuth2Provider,
		Optional<RouterFunctionProvider> routerFunctionProvider, Optional<RepositoryRestResourceProvider> repositoryRestResourceProvider) {
	return new OpenApiResource(DEFAULT_GROUP_NAME, openAPIBuilderObjectFactory, requestBuilder, responseBuilder, operationParser, requestMappingHandlerMapping,
			actuatorProvider,operationCustomizers, openApiCustomisers, springDocConfigProperties, springSecurityOAuth2Provider,routerFunctionProvider, repositoryRestResourceProvider);
}
 
Example #23
Source File: DefaultSingletonBeanRegistryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testSingletons() {
	DefaultSingletonBeanRegistry beanRegistry = new DefaultSingletonBeanRegistry();

	TestBean tb = new TestBean();
	beanRegistry.registerSingleton("tb", tb);
	assertSame(tb, beanRegistry.getSingleton("tb"));

	TestBean tb2 = (TestBean) beanRegistry.getSingleton("tb2", new ObjectFactory<Object>() {
		@Override
		public Object getObject() throws BeansException {
			return new TestBean();
		}
	});
	assertSame(tb2, beanRegistry.getSingleton("tb2"));

	assertSame(tb, beanRegistry.getSingleton("tb"));
	assertSame(tb2, beanRegistry.getSingleton("tb2"));
	assertEquals(2, beanRegistry.getSingletonCount());
	String[] names = beanRegistry.getSingletonNames();
	assertEquals(2, names.length);
	assertEquals("tb", names[0]);
	assertEquals("tb2", names[1]);

	beanRegistry.destroySingletons();
	assertEquals(0, beanRegistry.getSingletonCount());
	assertEquals(0, beanRegistry.getSingletonNames().length);
}
 
Example #24
Source File: ThreadLocalScope.java    From geekbang-lessons with Apache License 2.0 5 votes vote down vote up
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {

    // 非空
    Map<String, Object> context = getContext();

    Object object = context.get(name);

    if (object == null) {
        object = objectFactory.getObject();
        context.put(name, object);
    }

    return object;
}
 
Example #25
Source File: CommonAnnotationBeanPostProcessorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testResourceInjectionWithResolvableDependencyType() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	CommonAnnotationBeanPostProcessor bpp = new CommonAnnotationBeanPostProcessor();
	bpp.setBeanFactory(bf);
	bf.addBeanPostProcessor(bpp);
	RootBeanDefinition abd = new RootBeanDefinition(ExtendedResourceInjectionBean.class);
	abd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
	bf.registerBeanDefinition("annotatedBean", abd);
	RootBeanDefinition tbd = new RootBeanDefinition(TestBean.class);
	tbd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
	bf.registerBeanDefinition("testBean4", tbd);

	bf.registerResolvableDependency(BeanFactory.class, bf);
	bf.registerResolvableDependency(INestedTestBean.class, new ObjectFactory<Object>() {
		@Override
		public Object getObject() throws BeansException {
			return new NestedTestBean();
		}
	});

	PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
	Properties props = new Properties();
	props.setProperty("tb", "testBean4");
	ppc.setProperties(props);
	ppc.postProcessBeanFactory(bf);

	ExtendedResourceInjectionBean bean = (ExtendedResourceInjectionBean) bf.getBean("annotatedBean");
	INestedTestBean tb = bean.getTestBean6();
	assertNotNull(tb);

	ExtendedResourceInjectionBean anotherBean = (ExtendedResourceInjectionBean) bf.getBean("annotatedBean");
	assertNotSame(anotherBean, bean);
	assertNotSame(anotherBean.getTestBean6(), tb);

	String[] depBeans = bf.getDependenciesForBean("annotatedBean");
	assertEquals(1, depBeans.length);
	assertEquals("testBean4", depBeans[0]);
}
 
Example #26
Source File: ResourceAdapterApplicationContext.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
	beanFactory.addBeanPostProcessor(new BootstrapContextAwareProcessor(this.bootstrapContext));
	beanFactory.ignoreDependencyInterface(BootstrapContextAware.class);
	beanFactory.registerResolvableDependency(BootstrapContext.class, this.bootstrapContext);

	// JCA WorkManager resolved lazily - may not be available.
	beanFactory.registerResolvableDependency(WorkManager.class,
			(ObjectFactory<WorkManager>) this.bootstrapContext::getWorkManager);
}
 
Example #27
Source File: SimpleTransactionScope.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
	ScopedObjectsHolder scopedObjects = (ScopedObjectsHolder) TransactionSynchronizationManager.getResource(this);
	if (scopedObjects == null) {
		scopedObjects = new ScopedObjectsHolder();
		TransactionSynchronizationManager.registerSynchronization(new CleanupSynchronization(scopedObjects));
		TransactionSynchronizationManager.bindResource(this, scopedObjects);
	}
	Object scopedObject = scopedObjects.scopedInstances.get(name);
	if (scopedObject == null) {
		scopedObject = objectFactory.getObject();
		scopedObjects.scopedInstances.put(name, scopedObject);
	}
	return scopedObject;
}
 
Example #28
Source File: SimpleMapScope.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
	synchronized (this.map) {
		Object scopedObject = this.map.get(name);
		if (scopedObject == null) {
			scopedObject = objectFactory.getObject();
			this.map.put(name, scopedObject);
		}
		return scopedObject;
	}
}
 
Example #29
Source File: AnnotationDrivenEventListenerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
	Assert.state(this.active, "Not active");
	if (this.instance == null) {
		this.instance = objectFactory.getObject();
	}
	return this.instance;
}
 
Example #30
Source File: ObjectFactoryCreatingFactoryBean.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected ObjectFactory<Object> createInstance() {
	BeanFactory beanFactory = getBeanFactory();
	Assert.state(beanFactory != null, "No BeanFactory available");
	Assert.state(this.targetBeanName != null, "No target bean name specified");
	return new TargetBeanObjectFactory(beanFactory, this.targetBeanName);
}