Java Code Examples for org.springframework.beans.factory.ObjectFactory

The following examples show how to use org.springframework.beans.factory.ObjectFactory. These examples are extracted from open source projects. 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 Project: spring-analysis-note   Source File: SimpSessionScope.java    License: 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 2
Source Project: spring-analysis-note   Source File: ScopingTests.java    License: 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 3
@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 4
Source Project: spring-analysis-note   Source File: WebApplicationContextUtils.java    License: 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 5
/**
 * 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 6
@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 7
Source Project: springdoc-openapi   Source File: OpenApiResource.java    License: 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 8
Source Project: springdoc-openapi   Source File: MultipleOpenApiResource.java    License: 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 9
/**
 * 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 10
/**
 * 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 11
@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 12
Source Project: java-technology-stack   Source File: ScopingTests.java    License: 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 13
@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 14
Source Project: java-technology-stack   Source File: WebApplicationContextUtils.java    License: 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 15
/**
 * 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 16
Source Project: java-technology-stack   Source File: DefaultListableBeanFactory.java    License: 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 17
Source Project: XS2A-Sandbox   Source File: TppUiBeFeignConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public Encoder feignEncoder() {
    objectMapper.addMixIn(ScaUserDataTO.class, ScaUserDataMixedIn.class)
        .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter(objectMapper);
    ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(jacksonConverter);
    return new SpringEncoder(objectFactory);
}
 
Example 18
Source Project: XS2A-Sandbox   Source File: FeignConfig.java    License: 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 Project: spring-analysis-note   Source File: SimpSessionScopeTests.java    License: MIT License 5 votes vote down vote up
@Before
public void setUp() {
	this.scope = new SimpSessionScope();
	this.objectFactory = Mockito.mock(ObjectFactory.class);
	this.simpAttributes = new SimpAttributes("session1", new ConcurrentHashMap<>());
	SimpAttributesContextHolder.setAttributes(this.simpAttributes);
}
 
Example 20
Source Project: spring-analysis-note   Source File: SimpleThreadScope.java    License: MIT License 5 votes vote down vote up
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
	Map<String, Object> scope = this.threadScope.get();
	Object scopedObject = scope.get(name);
	if (scopedObject == null) {
		scopedObject = objectFactory.getObject();
		scope.put(name, scopedObject);
	}
	return scopedObject;
}
 
Example 21
@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 22
@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 23
Source Project: spring-analysis-note   Source File: SimpleMapScope.java    License: 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 24
Source Project: spring-analysis-note   Source File: SimpleTransactionScope.java    License: 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 25
@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 26
Source Project: spring-analysis-note   Source File: SessionScope.java    License: MIT License 5 votes vote down vote up
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
	Object mutex = RequestContextHolder.currentRequestAttributes().getSessionMutex();
	synchronized (mutex) {
		return super.get(name, objectFactory);
	}
}
 
Example 27
Source Project: spring-analysis-note   Source File: ServletContextScope.java    License: MIT License 5 votes vote down vote up
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
	Object scopedObject = this.servletContext.getAttribute(name);
	if (scopedObject == null) {
		scopedObject = objectFactory.getObject();
		this.servletContext.setAttribute(name, scopedObject);
	}
	return scopedObject;
}
 
Example 28
Source Project: spring-analysis-note   Source File: AutowireUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Resolve the given autowiring value against the given required type,
 * e.g. an {@link ObjectFactory} value to its actual object result.
 * @param autowiringValue the value to resolve
 * @param requiredType the type to assign the result to
 * @return the resolved value
 */
public static Object resolveAutowiringValue(Object autowiringValue, Class<?> requiredType) {
	if (autowiringValue instanceof ObjectFactory && !requiredType.isInstance(autowiringValue)) {
		ObjectFactory<?> factory = (ObjectFactory<?>) autowiringValue;
		if (autowiringValue instanceof Serializable && requiredType.isInterface()) {
			autowiringValue = Proxy.newProxyInstance(requiredType.getClassLoader(),
					new Class<?>[] {requiredType}, new ObjectFactoryDelegatingInvocationHandler(factory));
		}
		else {
			return factory.getObject();
		}
	}
	return autowiringValue;
}
 
Example 29
/**
 * 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) {
		// 判断 singletonObjects 不存在 beanName
		if (!this.singletonObjects.containsKey(beanName)) {
			// 注释 5.4 放入 beanName -> beanFactory,到时在 getSingleton() 获取单例时,可直接获取创建对应 bean 的工厂,解决循环依赖
			this.singletonFactories.put(beanName, singletonFactory);
			// 从提前曝光的缓存中移除,之前在 getSingleton() 放入的
			this.earlySingletonObjects.remove(beanName);
			// 往注册缓存中添加 beanName
			this.registeredSingletons.add(beanName);
		}
	}
}
 
Example 30
Source Project: spring-analysis-note   Source File: DefaultListableBeanFactory.java    License: 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);
	}
}