use of org.springframework.beans.factory.ObjectFactory in project spring-boot by spring-projects.
the class RestarterTests method getOrAddAttributeWithNewAttribute.
@Test
@SuppressWarnings("rawtypes")
public void getOrAddAttributeWithNewAttribute() throws Exception {
ObjectFactory objectFactory = mock(ObjectFactory.class);
given(objectFactory.getObject()).willReturn("abc");
Object attribute = Restarter.getInstance().getOrAddAttribute("x", objectFactory);
assertThat(attribute).isEqualTo("abc");
}
use of org.springframework.beans.factory.ObjectFactory in project spring-framework by spring-projects.
the class AbstractBeanFactory method doGetBean.
/**
* Return an instance, which may be shared or independent, of the specified bean.
* @param name the name of the bean to retrieve
* @param requiredType the required type of the bean to retrieve
* @param args arguments to use when creating a bean instance using explicit arguments
* (only applied when creating a new instance as opposed to retrieving an existing one)
* @param typeCheckOnly whether the instance is obtained for a type check,
* not for actual use
* @return an instance of the bean
* @throws BeansException if the bean could not be created
*/
@SuppressWarnings("unchecked")
protected <T> T doGetBean(final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException {
final String beanName = transformedBeanName(name);
Object bean;
// Eagerly check singleton cache for manually registered singletons.
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isDebugEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.debug("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference");
} else {
logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
} else {
// We're assumably within a circular reference.
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
if (args != null) {
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
} else {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
}
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try {
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
registerDependentBean(dep, beanName);
getBean(dep);
}
}
// Create bean instance.
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
try {
return createBean(beanName, mbd, args);
} catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
} else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
} finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
} else {
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
} finally {
afterPrototypeCreation(beanName);
}
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
} catch (IllegalStateException ex) {
throw new BeanCreationException(beanName, "Scope '" + scopeName + "' is not active for the current thread; consider " + "defining a scoped proxy for this bean if you intend to refer to it from a singleton", ex);
}
}
} catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
// Check if required type matches the type of the actual bean instance.
if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
try {
return getTypeConverter().convertIfNecessary(bean, requiredType);
} catch (TypeMismatchException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to convert bean '" + name + "' to required type '" + ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
use of org.springframework.beans.factory.ObjectFactory in project spring-framework by spring-projects.
the class DefaultSingletonBeanRegistryTests method testSingletons.
@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);
}
use of org.springframework.beans.factory.ObjectFactory in project spring-framework by spring-projects.
the class SimpleScopeTests method setUp.
@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);
}
use of org.springframework.beans.factory.ObjectFactory in project spring-boot by spring-projects.
the class MockRestarter method setup.
@SuppressWarnings("rawtypes")
private void setup() {
Restarter.setInstance(this.mock);
given(this.mock.getInitialUrls()).willReturn(new URL[] {});
given(this.mock.getOrAddAttribute(anyString(), (ObjectFactory) any())).willAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
String name = (String) invocation.getArguments()[0];
ObjectFactory factory = (ObjectFactory) invocation.getArguments()[1];
Object attribute = MockRestarter.this.attributes.get(name);
if (attribute == null) {
attribute = factory.getObject();
MockRestarter.this.attributes.put(name, attribute);
}
return attribute;
}
});
given(this.mock.getThreadFactory()).willReturn(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return new Thread(r);
}
});
}
Aggregations