Nullability fine-tuning around declaration inconsistencies

Issue: SPR-15720
Issue: SPR-15792
This commit is contained in:
Juergen Hoeller 2017-07-19 22:22:14 +02:00
parent 68e6b148cb
commit 46eba3dbfa
186 changed files with 986 additions and 619 deletions

View File

@ -31,9 +31,18 @@ import org.aopalliance.aop.Advice;
* implemented using interception.
*
* @author Rod Johnson
* @author Juergen Hoeller
*/
public interface Advisor {
/**
* Common placeholder for an empty {@code Advice} to be returned from
* {@link #getAdvice()} if no proper advice has been configured (yet).
* @since 5.0
*/
Advice EMPTY_ADVICE = new Advice() {};
/**
* Return the advice part of this aspect. An advice may be an
* interceptor, a before advice, a throws advice, etc.

View File

@ -23,7 +23,6 @@ import org.springframework.aop.PointcutAdvisor;
import org.springframework.core.Ordered;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
/**
* AspectJPointcutAdvisor that adapts an {@link AbstractAspectJAdvice}
@ -53,11 +52,11 @@ public class AspectJPointcutAdvisor implements PointcutAdvisor, Ordered {
this.pointcut = advice.buildSafePointcut();
}
public void setOrder(int order) {
this.order = order;
}
@Override
public boolean isPerInstance() {
return true;
@ -93,12 +92,12 @@ public class AspectJPointcutAdvisor implements PointcutAdvisor, Ordered {
return false;
}
AspectJPointcutAdvisor otherAdvisor = (AspectJPointcutAdvisor) other;
return (ObjectUtils.nullSafeEquals(this.advice, otherAdvisor.advice));
return this.advice.equals(otherAdvisor.advice);
}
@Override
public int hashCode() {
return AspectJPointcutAdvisor.class.hashCode();
return AspectJPointcutAdvisor.class.hashCode() * 29 + this.advice.hashCode();
}
}

View File

@ -39,11 +39,11 @@ public class AdvisorComponentDefinition extends AbstractComponentDefinition {
private final BeanDefinition advisorDefinition;
private String description;
private final String description;
private BeanReference[] beanReferences;
private final BeanReference[] beanReferences;
private BeanDefinition[] beanDefinitions;
private final BeanDefinition[] beanDefinitions;
public AdvisorComponentDefinition(String advisorBeanName, BeanDefinition advisorDefinition) {
@ -57,11 +57,7 @@ public class AdvisorComponentDefinition extends AbstractComponentDefinition {
Assert.notNull(advisorDefinition, "'advisorDefinition' must not be null");
this.advisorBeanName = advisorBeanName;
this.advisorDefinition = advisorDefinition;
unwrapDefinitions(advisorDefinition, pointcutDefinition);
}
private void unwrapDefinitions(BeanDefinition advisorDefinition, @Nullable BeanDefinition pointcutDefinition) {
MutablePropertyValues pvs = advisorDefinition.getPropertyValues();
BeanReference adviceReference = (BeanReference) pvs.get("adviceBeanName");
Assert.state(adviceReference != null, "Missing 'adviceBeanName' property");

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -21,6 +21,8 @@ import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.core.Ordered;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
@ -34,8 +36,10 @@ import org.springframework.util.StringUtils;
*/
public class SimpleBeanFactoryAwareAspectInstanceFactory implements AspectInstanceFactory, BeanFactoryAware {
@Nullable
private String aspectBeanName;
@Nullable
private BeanFactory beanFactory;
@ -50,9 +54,7 @@ public class SimpleBeanFactoryAwareAspectInstanceFactory implements AspectInstan
@Override
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
if (!StringUtils.hasText(this.aspectBeanName)) {
throw new IllegalArgumentException("'aspectBeanName' is required");
}
Assert.notNull(this.aspectBeanName, "'aspectBeanName' is required");
}
@ -62,6 +64,8 @@ public class SimpleBeanFactoryAwareAspectInstanceFactory implements AspectInstan
*/
@Override
public Object getAspectInstance() {
Assert.state(this.beanFactory != null, "No BeanFactory set");
Assert.state(this.aspectBeanName != null, "No 'aspectBeanName' set");
return this.beanFactory.getBean(this.aspectBeanName);
}
@ -77,7 +81,8 @@ public class SimpleBeanFactoryAwareAspectInstanceFactory implements AspectInstan
@Override
public int getOrder() {
if (this.beanFactory.isSingleton(this.aspectBeanName) &&
if (this.beanFactory != null && this.aspectBeanName != null &&
this.beanFactory.isSingleton(this.aspectBeanName) &&
this.beanFactory.isTypeMatch(this.aspectBeanName, Ordered.class)) {
return ((Ordered) this.beanFactory.getBean(this.aspectBeanName)).getOrder();
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -22,6 +22,7 @@ import java.util.concurrent.ConcurrentHashMap;
import org.springframework.aop.Advisor;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.lang.Nullable;
/**
* Base class for {@link BeanPostProcessor} implementations that apply a
@ -33,6 +34,7 @@ import org.springframework.beans.factory.config.BeanPostProcessor;
@SuppressWarnings("serial")
public abstract class AbstractAdvisingBeanPostProcessor extends ProxyProcessorSupport implements BeanPostProcessor {
@Nullable
protected Advisor advisor;
protected boolean beforeExistingAdvisors = false;
@ -61,7 +63,7 @@ public abstract class AbstractAdvisingBeanPostProcessor extends ProxyProcessorSu
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
if (bean instanceof AopInfrastructureBean) {
if (bean instanceof AopInfrastructureBean || this.advisor == null) {
// Ignore AOP infrastructure such as scoped proxies.
return bean;
}
@ -125,6 +127,9 @@ public abstract class AbstractAdvisingBeanPostProcessor extends ProxyProcessorSu
if (eligible != null) {
return eligible;
}
if (this.advisor == null) {
return false;
}
eligible = AopUtils.canApply(this.advisor, targetClass);
this.eligibleBeans.put(targetClass, eligible);
return eligible;

View File

@ -107,7 +107,7 @@ public class AdvisedSupport extends ProxyConfig implements Advised {
* No-arg constructor for use as a JavaBean.
*/
public AdvisedSupport() {
initMethodCache();
this.methodCache = new ConcurrentHashMap<>(32);
}
/**
@ -119,13 +119,6 @@ public class AdvisedSupport extends ProxyConfig implements Advised {
setInterfaces(interfaces);
}
/**
* Initialize the method cache.
*/
private void initMethodCache() {
this.methodCache = new ConcurrentHashMap<>(32);
}
/**
* Set the given object as target.
@ -558,7 +551,7 @@ public class AdvisedSupport extends ProxyConfig implements Advised {
ois.defaultReadObject();
// Initialize transient fields.
initMethodCache();
this.methodCache = new ConcurrentHashMap<>(32);
}

View File

@ -25,6 +25,7 @@ import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* Generic auto proxy creator that builds AOP proxies for specific beans
@ -48,6 +49,7 @@ import org.springframework.lang.Nullable;
@SuppressWarnings("serial")
public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyCreator {
@Nullable
private BeanFactoryAdvisorRetrievalHelper advisorRetrievalHelper;
@ -101,6 +103,7 @@ public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyC
* @return the List of candidate Advisors
*/
protected List<Advisor> findCandidateAdvisors() {
Assert.state(this.advisorRetrievalHelper != null, "No BeanFactoryAdvisorRetrievalHelper available");
return this.advisorRetrievalHelper.findAdvisorBeans();
}

View File

@ -203,7 +203,7 @@ public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
}
@Override
public void setBeanFactory(@Nullable BeanFactory beanFactory) {
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
@ -241,10 +241,10 @@ public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
}
@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, @Nullable String beanName) throws BeansException {
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
Object cacheKey = getCacheKey(beanClass, beanName);
if (beanName == null || !this.targetSourcedBeans.contains(beanName)) {
if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
if (this.advisedBeans.containsKey(cacheKey)) {
return null;
}
@ -257,15 +257,15 @@ public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
// Create proxy here if we have a custom TargetSource.
// Suppresses unnecessary default instantiation of the target bean:
// The TargetSource will handle target instances in a custom fashion.
if (beanName != null) {
TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
if (targetSource != null) {
TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
if (targetSource != null) {
if (StringUtils.hasLength(beanName)) {
this.targetSourcedBeans.add(beanName);
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}
return null;
@ -333,8 +333,8 @@ public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
* @param cacheKey the cache key for metadata access
* @return a proxy wrapping the bean, or the raw bean instance as-is
*/
protected Object wrapIfNecessary(Object bean, @Nullable String beanName, Object cacheKey) {
if (beanName != null && this.targetSourcedBeans.contains(beanName)) {
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
return bean;
}
if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
@ -391,7 +391,7 @@ public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
* @param beanName the name of the bean
* @return whether to skip the given bean
*/
protected boolean shouldSkip(Class<?> beanClass, @Nullable String beanName) {
protected boolean shouldSkip(Class<?> beanClass, String beanName) {
return false;
}
@ -582,8 +582,7 @@ public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
* @see #PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS
*/
@Nullable
protected abstract Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass,
@Nullable String beanName, @Nullable TargetSource customTargetSource)
throws BeansException;
protected abstract Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName,
@Nullable TargetSource customTargetSource) throws BeansException;
}

View File

@ -76,7 +76,9 @@ public class BeanNameAutoProxyCreator extends AbstractAutoProxyCreator {
*/
@Override
@Nullable
protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) {
protected Object[] getAdvicesAndAdvisorsForBean(
Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) {
if (this.beanNames != null) {
for (String mappedName : this.beanNames) {
if (FactoryBean.class.isAssignableFrom(beanClass)) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -18,6 +18,7 @@ package org.springframework.aop.framework.autoproxy;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.lang.Nullable;
/**
* Auto-proxy creator that considers infrastructure Advisor beans only,
@ -29,6 +30,7 @@ import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
@SuppressWarnings("serial")
public class InfrastructureAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreator {
@Nullable
private ConfigurableListableBeanFactory beanFactory;
@ -40,7 +42,7 @@ public class InfrastructureAdvisorAutoProxyCreator extends AbstractAdvisorAutoPr
@Override
protected boolean isEligibleAdvisorBean(String beanName) {
return (this.beanFactory.containsBeanDefinition(beanName) &&
return (this.beanFactory != null && this.beanFactory.containsBeanDefinition(beanName) &&
this.beanFactory.getBeanDefinition(beanName).getRole() == BeanDefinition.ROLE_INFRASTRUCTURE);
}

View File

@ -89,6 +89,7 @@ public abstract class AbstractExpressionPointcut implements ExpressionPointcut,
* Return this pointcut's expression.
*/
@Override
@Nullable
public String getExpression() {
return this.expression;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -19,7 +19,8 @@ package org.springframework.aop.support;
import org.aopalliance.aop.Advice;
/**
* Abstract generic PointcutAdvisor that allows for any Advice to be configured.
* Abstract generic {@link org.springframework.aop.PointcutAdvisor}
* that allows for any {@link Advice} to be configured.
*
* @author Juergen Hoeller
* @since 2.0
@ -29,7 +30,7 @@ import org.aopalliance.aop.Advice;
@SuppressWarnings("serial")
public abstract class AbstractGenericPointcutAdvisor extends AbstractPointcutAdvisor {
private Advice advice;
private Advice advice = EMPTY_ADVICE;
/**

View File

@ -57,6 +57,7 @@ public class DelegatingIntroductionInterceptor extends IntroductionInfoSupport
* Object that actually implements the interfaces.
* May be "this" if a subclass implements the introduced interfaces.
*/
@Nullable
private Object delegate;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -38,7 +38,7 @@ public abstract class StaticMethodMatcherPointcutAdvisor extends StaticMethodMat
private int order = Integer.MAX_VALUE;
private Advice advice;
private Advice advice = EMPTY_ADVICE;
/**

View File

@ -578,6 +578,7 @@ public abstract class AbstractNestablePropertyAccessor extends AbstractPropertyA
@Nullable Object newValue, @Nullable Class<?> requiredType, @Nullable TypeDescriptor td)
throws TypeMismatchException {
Assert.state(this.typeConverterDelegate != null, "No TypeConverterDelegate");
try {
return this.typeConverterDelegate.convertIfNecessary(propertyName, oldValue, newValue, requiredType, td);
}

View File

@ -33,8 +33,10 @@ public class BeanInstantiationException extends FatalBeanException {
private Class<?> beanClass;
@Nullable
private Constructor<?> constructor;
@Nullable
private Method constructingMethod;

View File

@ -22,6 +22,7 @@ import java.util.Map;
import org.springframework.core.ResolvableType;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.lang.Nullable;
import org.springframework.util.ReflectionUtils;
/**
@ -134,7 +135,7 @@ public class DirectFieldAccessor extends AbstractNestablePropertyAccessor {
}
@Override
public void setValue(Object value) throws Exception {
public void setValue(@Nullable Object value) throws Exception {
try {
ReflectionUtils.makeAccessible(this.field);
this.field.set(getWrappedInstance(), value);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -22,6 +22,7 @@ import org.springframework.core.MethodParameter;
import org.springframework.core.convert.ConversionException;
import org.springframework.core.convert.ConverterNotFoundException;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* Base implementation of the {@link TypeConverter} interface, using a package-private delegate.
@ -33,6 +34,7 @@ import org.springframework.lang.Nullable;
*/
public abstract class TypeConverterSupport extends PropertyEditorRegistrySupport implements TypeConverter {
@Nullable
TypeConverterDelegate typeConverterDelegate;
@ -59,6 +61,7 @@ public abstract class TypeConverterSupport extends PropertyEditorRegistrySupport
private <T> T doConvert(@Nullable Object value,@Nullable Class<T> requiredType,
@Nullable MethodParameter methodParam, @Nullable Field field) throws TypeMismatchException {
Assert.state(this.typeConverterDelegate != null, "No TypeConverterDelegate");
try {
if (field != null) {
return this.typeConverterDelegate.convertIfNecessary(value, requiredType, field);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -35,6 +35,7 @@ public class NoUniqueBeanDefinitionException extends NoSuchBeanDefinitionExcepti
private int numberOfBeansFound;
@Nullable
private Collection<String> beanNamesFound;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -20,6 +20,7 @@ import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.MethodMetadata;
import org.springframework.core.type.StandardAnnotationMetadata;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
@ -44,6 +45,7 @@ public class AnnotatedGenericBeanDefinition extends GenericBeanDefinition implem
private final AnnotationMetadata metadata;
@Nullable
private MethodMetadata factoryMethodMetadata;
@ -98,6 +100,7 @@ public class AnnotatedGenericBeanDefinition extends GenericBeanDefinition implem
}
@Override
@Nullable
public final MethodMetadata getFactoryMethodMetadata() {
return this.factoryMethodMetadata;
}

View File

@ -89,6 +89,7 @@ public class RequiredAnnotationBeanPostProcessor extends InstantiationAwareBeanP
private int order = Ordered.LOWEST_PRECEDENCE - 1;
@Nullable
private ConfigurableListableBeanFactory beanFactory;
/**

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -22,6 +22,7 @@ import java.util.Properties;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.support.PropertiesLoaderSupport;
import org.springframework.lang.Nullable;
/**
* Allows for making a properties file from a classpath location available
@ -47,6 +48,7 @@ public class PropertiesFactoryBean extends PropertiesLoaderSupport
private boolean singleton = true;
@Nullable
private Properties singletonInstance;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -47,8 +47,7 @@ public class BeanComponentDefinition extends BeanDefinitionHolder implements Com
* @param beanName the name of the bean
*/
public BeanComponentDefinition(BeanDefinition beanDefinition, String beanName) {
super(beanDefinition, beanName);
findInnerBeanDefinitionsAndBeanReferences(beanDefinition);
this(new BeanDefinitionHolder(beanDefinition, beanName));
}
/**
@ -58,27 +57,21 @@ public class BeanComponentDefinition extends BeanDefinitionHolder implements Com
* @param aliases alias names for the bean, or {@code null} if none
*/
public BeanComponentDefinition(BeanDefinition beanDefinition, String beanName, @Nullable String[] aliases) {
super(beanDefinition, beanName, aliases);
findInnerBeanDefinitionsAndBeanReferences(beanDefinition);
this(new BeanDefinitionHolder(beanDefinition, beanName, aliases));
}
/**
* Create a new BeanComponentDefinition for the given bean.
* @param holder the BeanDefinitionHolder encapsulating the
* bean definition as well as the name of the bean
* @param beanDefinitionHolder the BeanDefinitionHolder encapsulating
* the bean definition as well as the name of the bean
*/
public BeanComponentDefinition(BeanDefinitionHolder holder) {
super(holder);
findInnerBeanDefinitionsAndBeanReferences(holder.getBeanDefinition());
}
public BeanComponentDefinition(BeanDefinitionHolder beanDefinitionHolder) {
super(beanDefinitionHolder);
private void findInnerBeanDefinitionsAndBeanReferences(BeanDefinition beanDefinition) {
List<BeanDefinition> innerBeans = new ArrayList<>();
List<BeanReference> references = new ArrayList<>();
PropertyValues propertyValues = beanDefinition.getPropertyValues();
for (int i = 0; i < propertyValues.getPropertyValues().length; i++) {
PropertyValue propertyValue = propertyValues.getPropertyValues()[i];
PropertyValues propertyValues = beanDefinitionHolder.getBeanDefinition().getPropertyValues();
for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {
Object value = propertyValue.getValue();
if (value instanceof BeanDefinitionHolder) {
innerBeans.add(((BeanDefinitionHolder) value).getBeanDefinition());

View File

@ -40,9 +40,7 @@ public class BeanDefinitionBuilder {
* Create a new {@code BeanDefinitionBuilder} used to construct a {@link GenericBeanDefinition}.
*/
public static BeanDefinitionBuilder genericBeanDefinition() {
BeanDefinitionBuilder builder = new BeanDefinitionBuilder();
builder.beanDefinition = new GenericBeanDefinition();
return builder;
return new BeanDefinitionBuilder(new GenericBeanDefinition());
}
/**
@ -50,8 +48,7 @@ public class BeanDefinitionBuilder {
* @param beanClassName the class name for the bean that the definition is being created for
*/
public static BeanDefinitionBuilder genericBeanDefinition(String beanClassName) {
BeanDefinitionBuilder builder = new BeanDefinitionBuilder();
builder.beanDefinition = new GenericBeanDefinition();
BeanDefinitionBuilder builder = new BeanDefinitionBuilder(new GenericBeanDefinition());
builder.beanDefinition.setBeanClassName(beanClassName);
return builder;
}
@ -61,8 +58,7 @@ public class BeanDefinitionBuilder {
* @param beanClass the {@code Class} of the bean that the definition is being created for
*/
public static BeanDefinitionBuilder genericBeanDefinition(Class<?> beanClass) {
BeanDefinitionBuilder builder = new BeanDefinitionBuilder();
builder.beanDefinition = new GenericBeanDefinition();
BeanDefinitionBuilder builder = new BeanDefinitionBuilder(new GenericBeanDefinition());
builder.beanDefinition.setBeanClass(beanClass);
return builder;
}
@ -76,8 +72,7 @@ public class BeanDefinitionBuilder {
public static <T> BeanDefinitionBuilder genericBeanDefinition(
@Nullable Class<T> beanClass, Supplier<T> instanceSupplier) {
BeanDefinitionBuilder builder = new BeanDefinitionBuilder();
builder.beanDefinition = new GenericBeanDefinition();
BeanDefinitionBuilder builder = new BeanDefinitionBuilder(new GenericBeanDefinition());
builder.beanDefinition.setBeanClass(beanClass);
builder.beanDefinition.setInstanceSupplier(instanceSupplier);
return builder;
@ -97,8 +92,7 @@ public class BeanDefinitionBuilder {
* @param factoryMethodName the name of the method to use to construct the bean instance
*/
public static BeanDefinitionBuilder rootBeanDefinition(String beanClassName, @Nullable String factoryMethodName) {
BeanDefinitionBuilder builder = new BeanDefinitionBuilder();
builder.beanDefinition = new RootBeanDefinition();
BeanDefinitionBuilder builder = new BeanDefinitionBuilder(new RootBeanDefinition());
builder.beanDefinition.setBeanClassName(beanClassName);
builder.beanDefinition.setFactoryMethodName(factoryMethodName);
return builder;
@ -118,8 +112,7 @@ public class BeanDefinitionBuilder {
* @param factoryMethodName the name of the method to use to construct the bean instance
*/
public static BeanDefinitionBuilder rootBeanDefinition(Class<?> beanClass, @Nullable String factoryMethodName) {
BeanDefinitionBuilder builder = new BeanDefinitionBuilder();
builder.beanDefinition = new RootBeanDefinition();
BeanDefinitionBuilder builder = new BeanDefinitionBuilder(new RootBeanDefinition());
builder.beanDefinition.setBeanClass(beanClass);
builder.beanDefinition.setFactoryMethodName(factoryMethodName);
return builder;
@ -130,16 +123,14 @@ public class BeanDefinitionBuilder {
* @param parentName the name of the parent bean
*/
public static BeanDefinitionBuilder childBeanDefinition(String parentName) {
BeanDefinitionBuilder builder = new BeanDefinitionBuilder();
builder.beanDefinition = new ChildBeanDefinition(parentName);
return builder;
return new BeanDefinitionBuilder(new ChildBeanDefinition(parentName));
}
/**
* The {@code BeanDefinition} instance we are creating.
*/
private AbstractBeanDefinition beanDefinition;
private final AbstractBeanDefinition beanDefinition;
/**
* Our current position with respect to constructor args.
@ -150,7 +141,8 @@ public class BeanDefinitionBuilder {
/**
* Enforce the use of factory methods.
*/
private BeanDefinitionBuilder() {
private BeanDefinitionBuilder(AbstractBeanDefinition beanDefinition) {
this.beanDefinition = beanDefinition;
}
/**

View File

@ -35,6 +35,7 @@ import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
@ -76,8 +77,10 @@ public class DefaultBeanDefinitionDocumentReader implements BeanDefinitionDocume
protected final Log logger = LogFactory.getLog(getClass());
@Nullable
private XmlReaderContext readerContext;
@Nullable
private BeanDefinitionParserDelegate delegate;
@ -99,6 +102,7 @@ public class DefaultBeanDefinitionDocumentReader implements BeanDefinitionDocume
* Return the descriptor for the XML resource that this parser works on.
*/
protected final XmlReaderContext getReaderContext() {
Assert.state(this.readerContext != null, "No XmlReaderContext available");
return this.readerContext;
}
@ -148,7 +152,7 @@ public class DefaultBeanDefinitionDocumentReader implements BeanDefinitionDocume
}
protected BeanDefinitionParserDelegate createDelegate(
XmlReaderContext readerContext, Element root, BeanDefinitionParserDelegate parentDelegate) {
XmlReaderContext readerContext, Element root, @Nullable BeanDefinitionParserDelegate parentDelegate) {
BeanDefinitionParserDelegate delegate = new BeanDefinitionParserDelegate(readerContext);
delegate.initDefaults(root, parentDelegate);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -18,6 +18,8 @@ package org.springframework.scheduling.commonj;
import commonj.timers.TimerListener;
import org.springframework.lang.Nullable;
/**
* JavaBean that describes a scheduled TimerListener, consisting of
* the TimerListener itself (or a Runnable to create a TimerListener for)
@ -40,6 +42,7 @@ import commonj.timers.TimerListener;
*/
public class ScheduledTimerListener {
@Nullable
private TimerListener timerListener;
private long delay = 0;
@ -140,13 +143,14 @@ public class ScheduledTimerListener {
/**
* Set the TimerListener to schedule.
*/
public void setTimerListener(TimerListener timerListener) {
public void setTimerListener(@Nullable TimerListener timerListener) {
this.timerListener = timerListener;
}
/**
* Return the TimerListener to schedule.
*/
@Nullable
public TimerListener getTimerListener() {
return this.timerListener;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -24,6 +24,7 @@ import freemarker.template.TemplateException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.lang.Nullable;
/**
* Factory bean that creates a FreeMarker Configuration and provides it as
@ -53,6 +54,7 @@ import org.springframework.context.ResourceLoaderAware;
public class FreeMarkerConfigurationFactoryBean extends FreeMarkerConfigurationFactory
implements FactoryBean<Configuration>, InitializingBean, ResourceLoaderAware {
@Nullable
private Configuration configuration;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -56,6 +56,7 @@ public class ConcurrentMapCacheManager implements CacheManager, BeanClassLoaderA
private boolean storeByValue = false;
@Nullable
private SerializationDelegate serialization;

View File

@ -38,7 +38,7 @@ public abstract class AbstractCacheInvoker {
}
protected AbstractCacheInvoker(CacheErrorHandler errorHandler) {
setErrorHandler(errorHandler);
this.errorHandler = errorHandler;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -36,6 +36,7 @@ import org.springframework.util.Assert;
*/
public abstract class AbstractCacheResolver implements CacheResolver, InitializingBean {
@Nullable
private CacheManager cacheManager;
@ -55,15 +56,16 @@ public abstract class AbstractCacheResolver implements CacheResolver, Initializi
}
/**
* Return the {@link CacheManager} that this instance use.
* Return the {@link CacheManager} that this instance uses.
*/
public CacheManager getCacheManager() {
Assert.state(this.cacheManager != null, "No CacheManager set");
return this.cacheManager;
}
@Override
public void afterPropertiesSet() {
Assert.notNull(this.cacheManager, "CacheManager must not be null");
Assert.notNull(this.cacheManager, "CacheManager is required");
}
@ -76,7 +78,7 @@ public abstract class AbstractCacheResolver implements CacheResolver, Initializi
else {
Collection<Cache> result = new ArrayList<>();
for (String cacheName : cacheNames) {
Cache cache = this.cacheManager.getCache(cacheName);
Cache cache = getCacheManager().getCache(cacheName);
if (cache == null) {
throw new IllegalArgumentException("Cannot find cache named '" +
cacheName + "' for " + context.getOperation());

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -19,6 +19,7 @@ package org.springframework.cache.interceptor;
import org.springframework.aop.ClassFilter;
import org.springframework.aop.Pointcut;
import org.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor;
import org.springframework.lang.Nullable;
/**
* Advisor driven by a {@link CacheOperationSource}, used to include a
@ -30,6 +31,7 @@ import org.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor;
@SuppressWarnings("serial")
public class BeanFactoryCacheOperationSourceAdvisor extends AbstractBeanFactoryPointcutAdvisor {
@Nullable
private CacheOperationSource cacheOperationSource;
private final CacheOperationSourcePointcut pointcut = new CacheOperationSourcePointcut() {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,6 +16,8 @@
package org.springframework.cache.interceptor;
import org.springframework.lang.Nullable;
/**
* Class describing a cache 'put' operation.
*
@ -26,6 +28,7 @@ package org.springframework.cache.interceptor;
*/
public class CachePutOperation extends CacheOperation {
@Nullable
private final String unless;
@ -38,6 +41,7 @@ public class CachePutOperation extends CacheOperation {
}
@Nullable
public String getUnless() {
return this.unless;
}
@ -48,6 +52,7 @@ public class CachePutOperation extends CacheOperation {
*/
public static class Builder extends CacheOperation.Builder {
@Nullable
private String unless;
public void setUnless(String unless) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,6 +16,8 @@
package org.springframework.cache.interceptor;
import org.springframework.lang.Nullable;
/**
* Class describing a cache 'cacheable' operation.
*
@ -26,6 +28,7 @@ package org.springframework.cache.interceptor;
*/
public class CacheableOperation extends CacheOperation {
@Nullable
private final String unless;
private final boolean sync;
@ -41,6 +44,7 @@ public class CacheableOperation extends CacheOperation {
}
@Nullable
public String getUnless() {
return this.unless;
}
@ -55,6 +59,7 @@ public class CacheableOperation extends CacheOperation {
*/
public static class Builder extends CacheOperation.Builder {
@Nullable
private String unless;
private boolean sync;

View File

@ -16,12 +16,12 @@
package org.springframework.cache.interceptor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import org.springframework.cache.CacheManager;
import org.springframework.lang.Nullable;
/**
* A {@link CacheResolver} that forces the resolution to a configurable
@ -32,6 +32,7 @@ import org.springframework.cache.CacheManager;
*/
public class NamedCacheResolver extends AbstractCacheResolver {
@Nullable
private Collection<String> cacheNames;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -17,6 +17,7 @@
package org.springframework.cache.interceptor;
import org.springframework.cache.Cache;
import org.springframework.lang.Nullable;
/**
* A simple {@link CacheErrorHandler} that does not handle the
@ -33,7 +34,7 @@ public class SimpleCacheErrorHandler implements CacheErrorHandler {
}
@Override
public void handleCachePutError(RuntimeException exception, Cache cache, Object key, Object value) {
public void handleCachePutError(RuntimeException exception, Cache cache, Object key, @Nullable Object value) {
throw exception;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2011 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -17,6 +17,7 @@
package org.springframework.cache.support;
import java.util.Collection;
import java.util.Collections;
import org.springframework.cache.Cache;
@ -29,7 +30,7 @@ import org.springframework.cache.Cache;
*/
public class SimpleCacheManager extends AbstractCacheManager {
private Collection<? extends Cache> caches;
private Collection<? extends Cache> caches = Collections.emptySet();
/**

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -53,6 +53,7 @@ final class ConfigurationClass {
private final Resource resource;
@Nullable
private String beanName;
private final Set<ConfigurationClass> importedBy = new LinkedHashSet<>(1);
@ -75,7 +76,7 @@ final class ConfigurationClass {
* @see ConfigurationClass#ConfigurationClass(Class, ConfigurationClass)
*/
public ConfigurationClass(MetadataReader metadataReader, String beanName) {
Assert.hasText(beanName, "Bean name must not be null");
Assert.notNull(beanName, "Bean name must not be null");
this.metadata = metadataReader.getAnnotationMetadata();
this.resource = metadataReader.getResource();
this.beanName = beanName;
@ -102,7 +103,7 @@ final class ConfigurationClass {
* @see ConfigurationClass#ConfigurationClass(Class, ConfigurationClass)
*/
public ConfigurationClass(Class<?> clazz, String beanName) {
Assert.hasText(beanName, "Bean name must not be null");
Assert.notNull(beanName, "Bean name must not be null");
this.metadata = new StandardAnnotationMetadata(clazz, true);
this.resource = new DescriptiveResource(clazz.getName());
this.beanName = beanName;
@ -113,7 +114,7 @@ final class ConfigurationClass {
* using the {@link Import} annotation or automatically processed as a nested
* configuration class (if imported is {@code true}).
* @param clazz the underlying {@link Class} to represent
* @param importedBy the configuration class importing this one or {@code null}
* @param importedBy the configuration class importing this one (or {@code null})
* @since 3.1.1
*/
public ConfigurationClass(Class<?> clazz, @Nullable ConfigurationClass importedBy) {
@ -129,7 +130,7 @@ final class ConfigurationClass {
* @see ConfigurationClass#ConfigurationClass(Class, ConfigurationClass)
*/
public ConfigurationClass(AnnotationMetadata metadata, String beanName) {
Assert.hasText(beanName, "Bean name must not be null");
Assert.notNull(beanName, "Bean name must not be null");
this.metadata = metadata;
this.resource = new DescriptiveResource(metadata.getClassName());
this.beanName = beanName;
@ -152,6 +153,7 @@ final class ConfigurationClass {
this.beanName = beanName;
}
@Nullable
public String getBeanName() {
return this.beanName;
}

View File

@ -31,7 +31,6 @@ import org.springframework.aop.framework.autoproxy.AutoProxyUtils;
import org.springframework.aop.scope.ScopedObject;
import org.springframework.aop.scope.ScopedProxyUtils;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.context.ApplicationContext;
@ -41,6 +40,7 @@ import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.MethodIntrospector;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
@ -56,6 +56,7 @@ public class EventListenerMethodProcessor implements SmartInitializingSingleton,
protected final Log logger = LogFactory.getLog(getClass());
@Nullable
private ConfigurableApplicationContext applicationContext;
private final EventExpressionEvaluator evaluator = new EventExpressionEvaluator();
@ -64,21 +65,28 @@ public class EventListenerMethodProcessor implements SmartInitializingSingleton,
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
public void setApplicationContext(ApplicationContext applicationContext) {
Assert.isTrue(applicationContext instanceof ConfigurableApplicationContext,
"ApplicationContext does not implement ConfigurableApplicationContext");
this.applicationContext = (ConfigurableApplicationContext) applicationContext;
}
private ConfigurableApplicationContext getApplicationContext() {
Assert.state(this.applicationContext != null, "No ApplicationContext set");
return this.applicationContext;
}
@Override
public void afterSingletonsInstantiated() {
List<EventListenerFactory> factories = getEventListenerFactories();
String[] beanNames = this.applicationContext.getBeanNamesForType(Object.class);
ConfigurableApplicationContext context = getApplicationContext();
String[] beanNames = context.getBeanNamesForType(Object.class);
for (String beanName : beanNames) {
if (!ScopedProxyUtils.isScopedTarget(beanName)) {
Class<?> type = null;
try {
type = AutoProxyUtils.determineTargetClass(this.applicationContext.getBeanFactory(), beanName);
type = AutoProxyUtils.determineTargetClass(context.getBeanFactory(), beanName);
}
catch (Throwable ex) {
// An unresolvable bean type, probably from a lazy bean - let's ignore it.
@ -90,8 +98,7 @@ public class EventListenerMethodProcessor implements SmartInitializingSingleton,
if (ScopedObject.class.isAssignableFrom(type)) {
try {
Class<?> targetClass = AutoProxyUtils.determineTargetClass(
this.applicationContext.getBeanFactory(),
ScopedProxyUtils.getTargetBeanName(beanName));
context.getBeanFactory(), ScopedProxyUtils.getTargetBeanName(beanName));
if (targetClass != null) {
type = targetClass;
}
@ -121,7 +128,7 @@ public class EventListenerMethodProcessor implements SmartInitializingSingleton,
* {@link EventListener} annotated methods.
*/
protected List<EventListenerFactory> getEventListenerFactories() {
Map<String, EventListenerFactory> beans = this.applicationContext.getBeansOfType(EventListenerFactory.class);
Map<String, EventListenerFactory> beans = getApplicationContext().getBeansOfType(EventListenerFactory.class);
List<EventListenerFactory> allFactories = new ArrayList<>(beans.values());
AnnotationAwareOrderComparator.sort(allFactories);
return allFactories;
@ -152,18 +159,17 @@ public class EventListenerMethodProcessor implements SmartInitializingSingleton,
}
else {
// Non-empty set of methods
ConfigurableApplicationContext context = getApplicationContext();
for (Method method : annotatedMethods.keySet()) {
for (EventListenerFactory factory : factories) {
if (factory.supportsMethod(method)) {
Method methodToUse = AopUtils.selectInvocableMethod(
method, this.applicationContext.getType(beanName));
Method methodToUse = AopUtils.selectInvocableMethod(method, context.getType(beanName));
ApplicationListener<?> applicationListener =
factory.createApplicationListener(beanName, targetType, methodToUse);
if (applicationListener instanceof ApplicationListenerMethodAdapter) {
((ApplicationListenerMethodAdapter) applicationListener)
.init(this.applicationContext, this.evaluator);
((ApplicationListenerMethodAdapter) applicationListener).init(context, this.evaluator);
}
this.applicationContext.addApplicationListener(applicationListener);
context.addApplicationListener(applicationListener);
break;
}
}

View File

@ -27,7 +27,6 @@ import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcess
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.lang.Nullable;
import org.springframework.util.ObjectUtils;
/**
@ -47,7 +46,6 @@ class ApplicationListenerDetector implements DestructionAwareBeanPostProcessor,
private static final Log logger = LogFactory.getLog(ApplicationListenerDetector.class);
@Nullable
private transient final AbstractApplicationContext applicationContext;
private transient final Map<String, Boolean> singletonNames = new ConcurrentHashMap<>(256);
@ -60,9 +58,7 @@ class ApplicationListenerDetector implements DestructionAwareBeanPostProcessor,
@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
if (this.applicationContext != null) {
this.singletonNames.put(beanName, beanDefinition.isSingleton());
}
this.singletonNames.put(beanName, beanDefinition.isSingleton());
}
@Override
@ -72,7 +68,7 @@ class ApplicationListenerDetector implements DestructionAwareBeanPostProcessor,
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
if (this.applicationContext != null && bean instanceof ApplicationListener) {
if (bean instanceof ApplicationListener) {
// potentially not detected as a listener by getBeanNamesForType retrieval
Boolean flag = this.singletonNames.get(beanName);
if (Boolean.TRUE.equals(flag)) {
@ -95,7 +91,7 @@ class ApplicationListenerDetector implements DestructionAwareBeanPostProcessor,
@Override
public void postProcessBeforeDestruction(Object bean, String beanName) {
if (this.applicationContext != null && bean instanceof ApplicationListener) {
if (bean instanceof ApplicationListener) {
ApplicationEventMulticaster multicaster = this.applicationContext.getApplicationEventMulticaster();
multicaster.removeApplicationListener((ApplicationListener<?>) bean);
multicaster.removeApplicationListenerBean(beanName);

View File

@ -51,6 +51,7 @@ import org.springframework.util.Assert;
*/
public class ClassPathXmlApplicationContext extends AbstractXmlApplicationContext {
@Nullable
private Resource[] configResources;
@ -203,6 +204,7 @@ public class ClassPathXmlApplicationContext extends AbstractXmlApplicationContex
@Override
@Nullable
protected Resource[] getConfigResources() {
return this.configResources;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -24,6 +24,7 @@ import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.ConversionServiceFactory;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.lang.Nullable;
/**
* A factory providing convenient access to a ConversionService configured with
@ -49,8 +50,10 @@ import org.springframework.core.convert.support.GenericConversionService;
*/
public class ConversionServiceFactoryBean implements FactoryBean<ConversionService>, InitializingBean {
@Nullable
private Set<?> converters;
@Nullable
private GenericConversionService conversionService;

View File

@ -39,6 +39,8 @@ import org.springframework.context.Lifecycle;
import org.springframework.context.LifecycleProcessor;
import org.springframework.context.Phased;
import org.springframework.context.SmartLifecycle;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* Default implementation of the {@link LifecycleProcessor} strategy.
@ -55,6 +57,7 @@ public class DefaultLifecycleProcessor implements LifecycleProcessor, BeanFactor
private volatile boolean running;
@Nullable
private volatile ConfigurableListableBeanFactory beanFactory;
@ -76,6 +79,12 @@ public class DefaultLifecycleProcessor implements LifecycleProcessor, BeanFactor
this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
}
private ConfigurableListableBeanFactory getBeanFactory() {
ConfigurableListableBeanFactory beanFactory = this.beanFactory;
Assert.state(beanFactory != null, "No BeanFactory available");
return beanFactory;
}
// Lifecycle implementation
@ -161,7 +170,7 @@ public class DefaultLifecycleProcessor implements LifecycleProcessor, BeanFactor
private void doStart(Map<String, ? extends Lifecycle> lifecycleBeans, String beanName, boolean autoStartupOnly) {
Lifecycle bean = lifecycleBeans.remove(beanName);
if (bean != null && !this.equals(bean)) {
String[] dependenciesForBean = this.beanFactory.getDependenciesForBean(beanName);
String[] dependenciesForBean = getBeanFactory().getDependenciesForBean(beanName);
for (String dependency : dependenciesForBean) {
doStart(lifecycleBeans, dependency, autoStartupOnly);
}
@ -215,7 +224,7 @@ public class DefaultLifecycleProcessor implements LifecycleProcessor, BeanFactor
Lifecycle bean = lifecycleBeans.remove(beanName);
if (bean != null) {
String[] dependentBeans = this.beanFactory.getDependentBeans(beanName);
String[] dependentBeans = getBeanFactory().getDependentBeans(beanName);
for (String dependentBean : dependentBeans) {
doStop(lifecycleBeans, dependentBean, latch, countDownBeanNames);
}
@ -266,16 +275,17 @@ public class DefaultLifecycleProcessor implements LifecycleProcessor, BeanFactor
* @return the Map of applicable beans, with bean names as keys and bean instances as values
*/
protected Map<String, Lifecycle> getLifecycleBeans() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
Map<String, Lifecycle> beans = new LinkedHashMap<>();
String[] beanNames = this.beanFactory.getBeanNamesForType(Lifecycle.class, false, false);
String[] beanNames = getBeanFactory().getBeanNamesForType(Lifecycle.class, false, false);
for (String beanName : beanNames) {
String beanNameToRegister = BeanFactoryUtils.transformedBeanName(beanName);
boolean isFactoryBean = this.beanFactory.isFactoryBean(beanNameToRegister);
boolean isFactoryBean = getBeanFactory().isFactoryBean(beanNameToRegister);
String beanNameToCheck = (isFactoryBean ? BeanFactory.FACTORY_BEAN_PREFIX + beanName : beanName);
if ((this.beanFactory.containsSingleton(beanNameToRegister) &&
if ((getBeanFactory().containsSingleton(beanNameToRegister) &&
(!isFactoryBean || matchesBeanType(Lifecycle.class, beanNameToCheck))) ||
matchesBeanType(SmartLifecycle.class, beanNameToCheck)) {
Lifecycle bean = this.beanFactory.getBean(beanNameToCheck, Lifecycle.class);
Lifecycle bean = getBeanFactory().getBean(beanNameToCheck, Lifecycle.class);
if (bean != this) {
beans.put(beanNameToRegister, bean);
}
@ -285,7 +295,7 @@ public class DefaultLifecycleProcessor implements LifecycleProcessor, BeanFactor
}
private boolean matchesBeanType(Class<?> targetType, String beanName) {
Class<?> beanType = this.beanFactory.getType(beanName);
Class<?> beanType = getBeanFactory().getType(beanName);
return (beanType != null && targetType.isAssignableFrom(beanType));
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -47,8 +47,10 @@ public class AspectJWeavingEnabler
public static final String ASPECTJ_AOP_XML_RESOURCE = "META-INF/aop.xml";
@Nullable
private ClassLoader beanClassLoader;
@Nullable
private LoadTimeWeaver loadTimeWeaver;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -20,6 +20,7 @@ import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.lang.Nullable;
/**
* {@link FactoryBean} that creates a Joda-Time {@link DateTimeFormatter}.
@ -36,6 +37,7 @@ import org.springframework.beans.factory.InitializingBean;
public class DateTimeFormatterFactoryBean extends DateTimeFormatterFactory
implements FactoryBean<DateTimeFormatter>, InitializingBean {
@Nullable
private DateTimeFormatter dateTimeFormatter;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -20,6 +20,7 @@ import java.time.format.DateTimeFormatter;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.lang.Nullable;
/**
* {@link FactoryBean} that creates a JSR-310 {@link java.time.format.DateTimeFormatter}.
@ -36,6 +37,7 @@ import org.springframework.beans.factory.InitializingBean;
public class DateTimeFormatterFactoryBean extends DateTimeFormatterFactory
implements FactoryBean<DateTimeFormatter>, InitializingBean {
@Nullable
private DateTimeFormatter dateTimeFormatter;

View File

@ -432,7 +432,8 @@ public class MetadataMBeanInfoAssembler extends AbstractReflectiveMBeanInfoAssem
* @param setter the Object value associated with the set method
* @return the appropriate Object to use as the value for the descriptor
*/
private Object resolveObjectDescriptor(@Nullable Object getter, Object setter) {
@Nullable
private Object resolveObjectDescriptor(@Nullable Object getter, @Nullable Object setter) {
return (getter != null ? getter : setter);
}
@ -446,7 +447,8 @@ public class MetadataMBeanInfoAssembler extends AbstractReflectiveMBeanInfoAssem
* @param setter the String value associated with the set method
* @return the appropriate String to use as the value for the descriptor
*/
private String resolveStringDescriptor(String getter, String setter) {
@Nullable
private String resolveStringDescriptor(@Nullable String getter, @Nullable String setter) {
return (StringUtils.hasLength(getter) ? getter : setter);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,6 +16,8 @@
package org.springframework.jmx.export.metadata;
import org.springframework.lang.Nullable;
/**
* Metadata that indicates to expose a given bean property as JMX attribute.
* Only valid when used on a JavaBean getter or setter.
@ -30,8 +32,10 @@ public class ManagedAttribute extends AbstractJmxAttribute {
public static final ManagedAttribute EMPTY = new ManagedAttribute();
@Nullable
private Object defaultValue;
@Nullable
private String persistPolicy;
private int persistPeriod = -1;
@ -40,21 +44,23 @@ public class ManagedAttribute extends AbstractJmxAttribute {
/**
* Set the default value of this attribute.
*/
public void setDefaultValue(Object defaultValue) {
public void setDefaultValue(@Nullable Object defaultValue) {
this.defaultValue = defaultValue;
}
/**
* Return the default value of this attribute.
*/
@Nullable
public Object getDefaultValue() {
return this.defaultValue;
}
public void setPersistPolicy(String persistPolicy) {
public void setPersistPolicy(@Nullable String persistPolicy) {
this.persistPolicy = persistPolicy;
}
@Nullable
public String getPersistPolicy() {
return this.persistPolicy;
}

View File

@ -17,6 +17,7 @@
package org.springframework.jmx.export.metadata;
import org.springframework.jmx.support.MetricType;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
@ -30,29 +31,34 @@ import org.springframework.util.Assert;
*/
public class ManagedMetric extends AbstractJmxAttribute {
@Nullable
private String category;
@Nullable
private String displayName;
private MetricType metricType = MetricType.GAUGE;
private int persistPeriod = -1;
@Nullable
private String persistPolicy;
@Nullable
private String unit;
/**
* The category of this metric (ex. throughput, performance, utilization).
*/
public void setCategory(String category) {
public void setCategory(@Nullable String category) {
this.category = category;
}
/**
* The category of this metric (ex. throughput, performance, utilization).
*/
@Nullable
public String getCategory() {
return this.category;
}
@ -60,13 +66,14 @@ public class ManagedMetric extends AbstractJmxAttribute {
/**
* A display name for this metric.
*/
public void setDisplayName(String displayName) {
public void setDisplayName(@Nullable String displayName) {
this.displayName = displayName;
}
/**
* A display name for this metric.
*/
@Nullable
public String getDisplayName() {
return this.displayName;
}
@ -103,13 +110,14 @@ public class ManagedMetric extends AbstractJmxAttribute {
/**
* The persist policy for this metric.
*/
public void setPersistPolicy(String persistPolicy) {
public void setPersistPolicy(@Nullable String persistPolicy) {
this.persistPolicy = persistPolicy;
}
/**
* The persist policy for this metric.
*/
@Nullable
public String getPersistPolicy() {
return this.persistPolicy;
}
@ -117,13 +125,14 @@ public class ManagedMetric extends AbstractJmxAttribute {
/**
* The expected unit of measurement values.
*/
public void setUnit(String unit) {
public void setUnit(@Nullable String unit) {
this.unit = unit;
}
/**
* The expected unit of measurement values.
*/
@Nullable
public String getUnit() {
return this.unit;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,6 +16,8 @@
package org.springframework.jmx.export.metadata;
import org.springframework.lang.Nullable;
/**
* Metadata indicating that instances of an annotated class
* are to be registered with a JMX server.
@ -29,31 +31,37 @@ package org.springframework.jmx.export.metadata;
*/
public class ManagedResource extends AbstractJmxAttribute {
@Nullable
private String objectName;
private boolean log = false;
@Nullable
private String logFile;
@Nullable
private String persistPolicy;
private int persistPeriod = -1;
@Nullable
private String persistName;
@Nullable
private String persistLocation;
/**
* Set the JMX ObjectName of this managed resource.
*/
public void setObjectName(String objectName) {
public void setObjectName(@Nullable String objectName) {
this.objectName = objectName;
}
/**
* Return the JMX ObjectName of this managed resource.
*/
@Nullable
public String getObjectName() {
return this.objectName;
}
@ -66,18 +74,20 @@ public class ManagedResource extends AbstractJmxAttribute {
return this.log;
}
public void setLogFile(String logFile) {
public void setLogFile(@Nullable String logFile) {
this.logFile = logFile;
}
@Nullable
public String getLogFile() {
return this.logFile;
}
public void setPersistPolicy(String persistPolicy) {
public void setPersistPolicy(@Nullable String persistPolicy) {
this.persistPolicy = persistPolicy;
}
@Nullable
public String getPersistPolicy() {
return this.persistPolicy;
}
@ -90,18 +100,20 @@ public class ManagedResource extends AbstractJmxAttribute {
return this.persistPeriod;
}
public void setPersistName(String persistName) {
public void setPersistName(@Nullable String persistName) {
this.persistName = persistName;
}
@Nullable
public String getPersistName() {
return this.persistName;
}
public void setPersistLocation(String persistLocation) {
public void setPersistLocation(@Nullable String persistLocation) {
this.persistLocation = persistLocation;
}
@Nullable
public String getPersistLocation() {
return this.persistLocation;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -29,9 +29,9 @@ import javax.naming.NamingException;
@SuppressWarnings("serial")
public class TypeMismatchNamingException extends NamingException {
private Class<?> requiredType;
private final Class<?> requiredType;
private Class<?> actualType;
private final Class<?> actualType;
/**
@ -48,14 +48,6 @@ public class TypeMismatchNamingException extends NamingException {
this.actualType = actualType;
}
/**
* Construct a new TypeMismatchNamingException.
* @param explanation the explanation text
*/
public TypeMismatchNamingException(String explanation) {
super(explanation);
}
/**
* Return the required type for the lookup, if available.

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -20,6 +20,7 @@ import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* Encapsulates a remote invocation result, holding a result value or an exception.
@ -53,7 +54,7 @@ public class RemoteInvocationResult implements Serializable {
* @param value the result value returned by a successful invocation
* of the target method
*/
public RemoteInvocationResult(Object value) {
public RemoteInvocationResult(@Nullable Object value) {
this.value = value;
}
@ -62,7 +63,7 @@ public class RemoteInvocationResult implements Serializable {
* @param exception the exception thrown by an unsuccessful invocation
* of the target method
*/
public RemoteInvocationResult(Throwable exception) {
public RemoteInvocationResult(@Nullable Throwable exception) {
this.exception = exception;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -88,17 +88,19 @@ public class ConcurrentTaskExecutor implements AsyncListenableTaskExecutor, Sche
* @see java.util.concurrent.Executors#newSingleThreadExecutor()
*/
public ConcurrentTaskExecutor() {
setConcurrentExecutor(null);
this.concurrentExecutor = Executors.newSingleThreadExecutor();
this.adaptedExecutor = new TaskExecutorAdapter(this.concurrentExecutor);
}
/**
* Create a new ConcurrentTaskExecutor, using the given {@link java.util.concurrent.Executor}.
* <p>Autodetects a JSR-236 {@link javax.enterprise.concurrent.ManagedExecutorService}
* in order to expose {@link javax.enterprise.concurrent.ManagedTask} adapters for it.
* @param concurrentExecutor the {@link java.util.concurrent.Executor} to delegate to
* @param executor the {@link java.util.concurrent.Executor} to delegate to
*/
public ConcurrentTaskExecutor(Executor concurrentExecutor) {
setConcurrentExecutor(concurrentExecutor);
public ConcurrentTaskExecutor(@Nullable Executor executor) {
this.concurrentExecutor = (executor != null ? executor : Executors.newSingleThreadExecutor());
this.adaptedExecutor = getAdaptedExecutor(this.concurrentExecutor);
}
@ -107,20 +109,9 @@ public class ConcurrentTaskExecutor implements AsyncListenableTaskExecutor, Sche
* <p>Autodetects a JSR-236 {@link javax.enterprise.concurrent.ManagedExecutorService}
* in order to expose {@link javax.enterprise.concurrent.ManagedTask} adapters for it.
*/
public final void setConcurrentExecutor(@Nullable Executor concurrentExecutor) {
if (concurrentExecutor != null) {
this.concurrentExecutor = concurrentExecutor;
if (managedExecutorServiceClass != null && managedExecutorServiceClass.isInstance(concurrentExecutor)) {
this.adaptedExecutor = new ManagedTaskExecutorAdapter(concurrentExecutor);
}
else {
this.adaptedExecutor = new TaskExecutorAdapter(concurrentExecutor);
}
}
else {
this.concurrentExecutor = Executors.newSingleThreadExecutor();
this.adaptedExecutor = new TaskExecutorAdapter(this.concurrentExecutor);
}
public final void setConcurrentExecutor(@Nullable Executor executor) {
this.concurrentExecutor = (executor != null ? executor : Executors.newSingleThreadExecutor());
this.adaptedExecutor = getAdaptedExecutor(this.concurrentExecutor);
}
/**
@ -184,6 +175,14 @@ public class ConcurrentTaskExecutor implements AsyncListenableTaskExecutor, Sche
}
private static TaskExecutorAdapter getAdaptedExecutor(Executor concurrentExecutor) {
if (managedExecutorServiceClass != null && managedExecutorServiceClass.isInstance(concurrentExecutor)) {
return new ManagedTaskExecutorAdapter(concurrentExecutor);
}
return new TaskExecutorAdapter(concurrentExecutor);
}
/**
* TaskExecutorAdapter subclass that wraps all provided Runnables and Callables
* with a JSR-236 ManagedTask, exposing a long-running hint based on

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -22,6 +22,7 @@ import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.lang.Nullable;
/**
* A Spring {@link FactoryBean} that builds and exposes a preconfigured {@link ForkJoinPool}.
@ -43,12 +44,14 @@ public class ForkJoinPoolFactoryBean implements FactoryBean<ForkJoinPool>, Initi
private ForkJoinPool.ForkJoinWorkerThreadFactory threadFactory = ForkJoinPool.defaultForkJoinWorkerThreadFactory;
@Nullable
private Thread.UncaughtExceptionHandler uncaughtExceptionHandler;
private boolean asyncMode = false;
private int awaitTerminationSeconds = 0;
@Nullable
private ForkJoinPool forkJoinPool;
@ -148,16 +151,18 @@ public class ForkJoinPoolFactoryBean implements FactoryBean<ForkJoinPool>, Initi
@Override
public void destroy() {
// Ignored for the common pool.
this.forkJoinPool.shutdown();
if (this.forkJoinPool != null) {
// Ignored for the common pool.
this.forkJoinPool.shutdown();
// Wait for all tasks to terminate - works for the common pool as well.
if (this.awaitTerminationSeconds > 0) {
try {
this.forkJoinPool.awaitTermination(this.awaitTerminationSeconds, TimeUnit.SECONDS);
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
// Wait for all tasks to terminate - works for the common pool as well.
if (this.awaitTerminationSeconds > 0) {
try {
this.forkJoinPool.awaitTermination(this.awaitTerminationSeconds, TimeUnit.SECONDS);
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
}

View File

@ -19,6 +19,7 @@ package org.springframework.scheduling.concurrent;
import java.util.concurrent.TimeUnit;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* JavaBean that describes a scheduled executor task, consisting of the
@ -40,6 +41,7 @@ import org.springframework.lang.Nullable;
*/
public class ScheduledExecutorTask {
@Nullable
private Runnable runnable;
private long delay = 0;
@ -107,6 +109,7 @@ public class ScheduledExecutorTask {
* Return the Runnable to schedule as executor task.
*/
public Runnable getRunnable() {
Assert.state(this.runnable != null, "No Runnable set");
return this.runnable;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -18,6 +18,7 @@ package org.springframework.scheduling.support;
import java.util.Date;
import org.springframework.lang.Nullable;
import org.springframework.scheduling.TriggerContext;
/**
@ -28,10 +29,13 @@ import org.springframework.scheduling.TriggerContext;
*/
public class SimpleTriggerContext implements TriggerContext {
@Nullable
private volatile Date lastScheduledExecutionTime;
@Nullable
private volatile Date lastActualExecutionTime;
@Nullable
private volatile Date lastCompletionTime;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -28,6 +28,7 @@ import org.springframework.lang.Nullable;
@SuppressWarnings("serial")
public class ScriptCompilationException extends NestedRuntimeException {
@Nullable
private ScriptSource scriptSource;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -38,6 +38,7 @@ import org.springframework.scripting.ScriptSource;
*/
public class BshScriptEvaluator implements ScriptEvaluator, BeanClassLoaderAware {
@Nullable
private ClassLoader classLoader;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -49,19 +49,19 @@ public class ExtendedModelMap extends ModelMap implements Model {
}
@Override
public ExtendedModelMap addAllAttributes(Collection<?> attributeValues) {
public ExtendedModelMap addAllAttributes(@Nullable Collection<?> attributeValues) {
super.addAllAttributes(attributeValues);
return this;
}
@Override
public ExtendedModelMap addAllAttributes(Map<String, ?> attributes) {
public ExtendedModelMap addAllAttributes(@Nullable Map<String, ?> attributes) {
super.addAllAttributes(attributes);
return this;
}
@Override
public ExtendedModelMap mergeAttributes(Map<String, ?> attributes) {
public ExtendedModelMap mergeAttributes(@Nullable Map<String, ?> attributes) {
super.mergeAttributes(attributes);
return this;
}

View File

@ -62,6 +62,7 @@ public class MethodValidationPostProcessor extends AbstractBeanFactoryAwareAdvis
private Class<? extends Annotation> validatedAnnotationType = Validated.class;
@Nullable
private Validator validator;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -43,9 +43,8 @@ public class AopNamespaceHandlerTests {
@Before
public void setUp() {
this.context =
new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-context.xml", getClass());
public void setup() {
this.context = new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-context.xml", getClass());
}
protected ITestBean getTestBean() {
@ -108,7 +107,27 @@ public class AopNamespaceHandlerTests {
}
@Test
public void testAspectAppliedForInitializeBean() {
public void testAspectAppliedForInitializeBeanWithEmptyName() {
ITestBean bean = (ITestBean) this.context.getAutowireCapableBeanFactory().initializeBean(new TestBean(), "");
CountingAspectJAdvice advice = (CountingAspectJAdvice) this.context.getBean("countingAdvice");
assertEquals("Incorrect before count", 0, advice.getBeforeCount());
assertEquals("Incorrect after count", 0, advice.getAfterCount());
bean.setName("Sally");
assertEquals("Incorrect before count", 1, advice.getBeforeCount());
assertEquals("Incorrect after count", 1, advice.getAfterCount());
bean.getName();
assertEquals("Incorrect before count", 1, advice.getBeforeCount());
assertEquals("Incorrect after count", 1, advice.getAfterCount());
}
@Test
public void testAspectAppliedForInitializeBeanWithNullName() {
ITestBean bean = (ITestBean) this.context.getAutowireCapableBeanFactory().initializeBean(new TestBean(), null);
CountingAspectJAdvice advice = (CountingAspectJAdvice) this.context.getBean("countingAdvice");
@ -126,6 +145,7 @@ public class AopNamespaceHandlerTests {
assertEquals("Incorrect before count", 1, advice.getBeforeCount());
assertEquals("Incorrect after count", 1, advice.getAfterCount());
}
}

View File

@ -30,10 +30,7 @@ import rx.RxReactiveStreams;
import org.springframework.lang.Nullable;
import static org.springframework.core.ReactiveTypeDescriptor.multiValue;
import static org.springframework.core.ReactiveTypeDescriptor.noValue;
import static org.springframework.core.ReactiveTypeDescriptor.singleOptionalValue;
import static org.springframework.core.ReactiveTypeDescriptor.singleRequiredValue;
import static org.springframework.core.ReactiveTypeDescriptor.*;
/**
* A registry of adapters to adapt a Reactive Streams {@link Publisher} to/from
@ -250,7 +247,7 @@ public class ReactiveAdapterRegistry {
}
@Override
public <T> Publisher<T> toPublisher(Object source) {
public <T> Publisher<T> toPublisher(@Nullable Object source) {
Publisher<T> publisher = super.toPublisher(source);
return (isMultiValue() ? Flux.from(publisher) : Mono.from(publisher));
}

View File

@ -47,7 +47,6 @@ final class AnnotationAttributesReadingVisitor extends RecursiveAnnotationAttrib
private final MultiValueMap<String, AnnotationAttributes> attributesMap;
@Nullable
private final Map<String, Set<String>> metaAnnotationMap;
@ -83,13 +82,11 @@ final class AnnotationAttributesReadingVisitor extends RecursiveAnnotationAttrib
}
}
}
if (this.metaAnnotationMap != null) {
Set<String> metaAnnotationTypeNames = new LinkedHashSet<>(visited.size());
for (Annotation ann : visited) {
metaAnnotationTypeNames.add(ann.annotationType().getName());
}
this.metaAnnotationMap.put(annotationClass.getName(), metaAnnotationTypeNames);
Set<String> metaAnnotationTypeNames = new LinkedHashSet<>(visited.size());
for (Annotation ann : visited) {
metaAnnotationTypeNames.add(ann.annotationType().getName());
}
this.metaAnnotationMap.put(annotationClass.getName(), metaAnnotationTypeNames);
}
}

View File

@ -66,6 +66,7 @@ class StaxEventXMLReader extends AbstractStaxXMLReader {
private String xmlVersion = DEFAULT_XML_VERSION;
@Nullable
private String encoding;
@ -77,7 +78,7 @@ class StaxEventXMLReader extends AbstractStaxXMLReader {
* @throws IllegalStateException if the reader is not at the start of a document or element
*/
StaxEventXMLReader(XMLEventReader reader) {
Assert.notNull(reader, "'reader' must not be null");
Assert.notNull(reader, "XMLEventReader must not be null");
try {
XMLEvent event = reader.peek();
if (event != null && !(event.isStartDocument() || event.isStartElement())) {
@ -189,6 +190,7 @@ class StaxEventXMLReader extends AbstractStaxXMLReader {
return xmlVersion;
}
@Override
@Nullable
public String getEncoding() {
return encoding;
}

View File

@ -48,22 +48,13 @@ import org.springframework.lang.Nullable;
*/
class StaxResult extends SAXResult {
@Nullable
private XMLEventWriter eventWriter;
@Nullable
private XMLStreamWriter streamWriter;
/**
* Construct a new instance of the {@code StaxResult} with the specified {@code XMLStreamWriter}.
* @param streamWriter the {@code XMLStreamWriter} to write to
*/
public StaxResult(XMLStreamWriter streamWriter) {
StaxStreamHandler handler = new StaxStreamHandler(streamWriter);
super.setHandler(handler);
super.setLexicalHandler(handler);
this.streamWriter = streamWriter;
}
/**
* Construct a new instance of the {@code StaxResult} with the specified {@code XMLEventWriter}.
* @param eventWriter the {@code XMLEventWriter} to write to
@ -75,6 +66,17 @@ class StaxResult extends SAXResult {
this.eventWriter = eventWriter;
}
/**
* Construct a new instance of the {@code StaxResult} with the specified {@code XMLStreamWriter}.
* @param streamWriter the {@code XMLStreamWriter} to write to
*/
public StaxResult(XMLStreamWriter streamWriter) {
StaxStreamHandler handler = new StaxStreamHandler(streamWriter);
super.setHandler(handler);
super.setLexicalHandler(handler);
this.streamWriter = streamWriter;
}
/**
* Return the {@code XMLEventWriter} used by this {@code StaxResult}.

View File

@ -47,23 +47,13 @@ import org.springframework.lang.Nullable;
*/
class StaxSource extends SAXSource {
@Nullable
private XMLEventReader eventReader;
@Nullable
private XMLStreamReader streamReader;
/**
* Construct a new instance of the {@code StaxSource} with the specified {@code XMLStreamReader}.
* The supplied stream reader must be in {@code XMLStreamConstants.START_DOCUMENT} or
* {@code XMLStreamConstants.START_ELEMENT} state.
* @param streamReader the {@code XMLStreamReader} to read from
* @throws IllegalStateException if the reader is not at the start of a document or element
*/
StaxSource(XMLStreamReader streamReader) {
super(new StaxStreamXMLReader(streamReader), new InputSource());
this.streamReader = streamReader;
}
/**
* Construct a new instance of the {@code StaxSource} with the specified {@code XMLEventReader}.
* The supplied event reader must be in {@code XMLStreamConstants.START_DOCUMENT} or
@ -76,6 +66,18 @@ class StaxSource extends SAXSource {
this.eventReader = eventReader;
}
/**
* Construct a new instance of the {@code StaxSource} with the specified {@code XMLStreamReader}.
* The supplied stream reader must be in {@code XMLStreamConstants.START_DOCUMENT} or
* {@code XMLStreamConstants.START_ELEMENT} state.
* @param streamReader the {@code XMLStreamReader} to read from
* @throws IllegalStateException if the reader is not at the start of a document or element
*/
StaxSource(XMLStreamReader streamReader) {
super(new StaxStreamXMLReader(streamReader), new InputSource());
this.streamReader = streamReader;
}
/**
* Return the {@code XMLEventReader} used by this {@code StaxSource}.

View File

@ -51,6 +51,7 @@ class StaxStreamXMLReader extends AbstractStaxXMLReader {
private String xmlVersion = DEFAULT_XML_VERSION;
@Nullable
private String encoding;
@ -62,7 +63,7 @@ class StaxStreamXMLReader extends AbstractStaxXMLReader {
* @throws IllegalStateException if the reader is not at the start of a document or element
*/
StaxStreamXMLReader(XMLStreamReader reader) {
Assert.notNull(reader, "'reader' must not be null");
Assert.notNull(reader, "XMLStreamReader must not be null");
int event = reader.getEventType();
if (!(event == XMLStreamConstants.START_DOCUMENT || event == XMLStreamConstants.START_ELEMENT)) {
throw new IllegalStateException("XMLEventReader not at start of document or element");
@ -166,6 +167,7 @@ class StaxStreamXMLReader extends AbstractStaxXMLReader {
return xmlVersion;
}
@Override
@Nullable
public String getEncoding() {
return encoding;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -22,6 +22,7 @@ import org.springframework.expression.TypedValue;
import org.springframework.expression.spel.CodeFlow;
import org.springframework.expression.spel.ExpressionState;
import org.springframework.expression.spel.SpelEvaluationException;
import org.springframework.lang.Nullable;
/**
* Represents a DOT separated expression sequence, such as 'property1.property2.methodOne()'
@ -91,7 +92,7 @@ public class CompoundExpression extends SpelNodeImpl {
}
@Override
public void setValue(ExpressionState state, Object value) throws EvaluationException {
public void setValue(ExpressionState state, @Nullable Object value) throws EvaluationException {
getValueRef(state).setValue(value);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -25,7 +25,8 @@ import org.springframework.expression.spel.ExpressionState;
import org.springframework.expression.spel.SpelEvaluationException;
import org.springframework.expression.spel.SpelMessage;
import org.springframework.expression.spel.support.BooleanTypedValue;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* The operator 'instanceof' checks if an object is of the class specified in the right
@ -36,8 +37,10 @@ import org.springframework.expression.spel.support.BooleanTypedValue;
*/
public class OperatorInstanceof extends Operator {
@Nullable
private Class<?> type;
public OperatorInstanceof(int pos, SpelNodeImpl... operands) {
super("instanceof", pos, operands);
}
@ -47,8 +50,8 @@ public class OperatorInstanceof extends Operator {
* Compare the left operand to see it is an instance of the type specified as the
* right operand. The right operand must be a class.
* @param state the expression state
* @return true if the left operand is an instanceof of the right operand, otherwise
* false
* @return {@code true} if the left operand is an instanceof of the right operand,
* otherwise {@code false}
* @throws EvaluationException if there is a problem evaluating the expression
*/
@Override
@ -58,7 +61,7 @@ public class OperatorInstanceof extends Operator {
TypedValue right = rightOperand.getValueInternal(state);
Object leftValue = left.getValue();
Object rightValue = right.getValue();
BooleanTypedValue result = null;
BooleanTypedValue result;
if (rightValue == null || !(rightValue instanceof Class)) {
throw new SpelEvaluationException(getRightOperand().getStartPosition(),
SpelMessage.INSTANCEOF_OPERATOR_NEEDS_CLASS_OPERAND,
@ -89,6 +92,7 @@ public class OperatorInstanceof extends Operator {
public void generateCode(MethodVisitor mv, CodeFlow cf) {
getLeftOperand().generateCode(mv, cf);
CodeFlow.insertBoxIfNecessary(mv, cf.lastDescriptor());
Assert.state(this.type != null, "No type available");
if (this.type.isPrimitive()) {
// always false - but left operand code always driven
// in case it had side effects
@ -96,7 +100,7 @@ public class OperatorInstanceof extends Operator {
mv.visitInsn(ICONST_0); // value of false
}
else {
mv.visitTypeInsn(INSTANCEOF,Type.getInternalName(this.type));
mv.visitTypeInsn(INSTANCEOF, Type.getInternalName(this.type));
}
cf.pushDescriptor(this.exitTypeDescriptor);
}

View File

@ -24,6 +24,7 @@ import org.springframework.expression.EvaluationException;
import org.springframework.expression.TypedValue;
import org.springframework.expression.spel.CodeFlow;
import org.springframework.expression.spel.ExpressionState;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
@ -35,15 +36,16 @@ public class TypeReference extends SpelNodeImpl {
private final int dimensions;
@Nullable
private transient Class<?> type;
public TypeReference(int pos, SpelNodeImpl qualifiedId) {
this(pos,qualifiedId,0);
this(pos, qualifiedId, 0);
}
public TypeReference(int pos, SpelNodeImpl qualifiedId, int dims) {
super(pos,qualifiedId);
super(pos, qualifiedId);
this.dimensions = dims;
}
@ -99,6 +101,7 @@ public class TypeReference extends SpelNodeImpl {
@Override
public void generateCode(MethodVisitor mv, CodeFlow cf) {
// TODO Future optimization - if followed by a static method call, skip generating code here
Assert.state(this.type != null, "No type available");
if (this.type.isPrimitive()) {
if (this.type == Integer.TYPE) {
mv.visitFieldInsn(GETSTATIC, "java/lang/Integer", "TYPE", "Ljava/lang/Class;");

View File

@ -68,7 +68,7 @@ public interface ValueRef {
}
@Override
public void setValue(Object newValue) {
public void setValue(@Nullable Object newValue) {
// The exception position '0' isn't right but the overhead of creating
// instances of this per node (where the node is solely for error reporting)
// would be unfortunate.
@ -102,7 +102,7 @@ public interface ValueRef {
}
@Override
public void setValue(Object newValue) {
public void setValue(@Nullable Object newValue) {
throw new SpelEvaluationException(this.node.pos, SpelMessage.NOT_ASSIGNABLE, this.node.toStringAST());
}

View File

@ -157,6 +157,7 @@ public class StandardEvaluationContext implements EvaluationContext {
}
@Override
@Nullable
public BeanResolver getBeanResolver() {
return this.beanResolver;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -19,6 +19,7 @@ package org.springframework.jdbc;
import java.sql.SQLException;
import org.springframework.dao.InvalidDataAccessResourceUsageException;
import org.springframework.lang.Nullable;
/**
* Exception thrown when a ResultSet has been accessed in an invalid fashion.
@ -35,6 +36,7 @@ import org.springframework.dao.InvalidDataAccessResourceUsageException;
@SuppressWarnings("serial")
public class InvalidResultSetAccessException extends InvalidDataAccessResourceUsageException {
@Nullable
private String sql;
@ -69,6 +71,7 @@ public class InvalidResultSetAccessException extends InvalidDataAccessResourceUs
* Return the SQL that caused the problem.
* @return the offending SQL, if known
*/
@Nullable
public String getSql() {
return this.sql;
}

View File

@ -515,6 +515,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
class BatchUpdateStatementCallback implements StatementCallback<int[]>, SqlProvider {
@Nullable
private String currSql;
@Override

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -21,6 +21,7 @@ import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.lang.Nullable;
/**
* Implementation of RowCallbackHandler. Convenient superclass for callback handlers.
@ -54,11 +55,13 @@ public class RowCountCallbackHandler implements RowCallbackHandler {
* Indexed from 0. Type (as in java.sql.Types) for the columns
* as returned by ResultSetMetaData object.
*/
@Nullable
private int[] columnTypes;
/**
* Indexed from 0. Column name as returned by ResultSetMetaData object.
*/
@Nullable
private String[] columnNames;
@ -102,8 +105,9 @@ public class RowCountCallbackHandler implements RowCallbackHandler {
* @return the types of the columns as java.sql.Types constants.
* <b>Indexed from 0 to n-1.</b>
*/
@Nullable
public final int[] getColumnTypes() {
return columnTypes;
return this.columnTypes;
}
/**
@ -112,8 +116,9 @@ public class RowCountCallbackHandler implements RowCallbackHandler {
* @return the names of the columns.
* <b>Indexed from 0 to n-1.</b>
*/
@Nullable
public final String[] getColumnNames() {
return columnNames;
return this.columnNames;
}
/**
@ -122,7 +127,7 @@ public class RowCountCallbackHandler implements RowCallbackHandler {
* @return the number of rows in this ResultSet
*/
public final int getRowCount() {
return rowCount;
return this.rowCount;
}
/**
@ -132,7 +137,7 @@ public class RowCountCallbackHandler implements RowCallbackHandler {
* @return the number of columns in this result set
*/
public final int getColumnCount() {
return columnCount;
return this.columnCount;
}
}

View File

@ -107,7 +107,7 @@ public class GenericCallMetaDataProvider implements CallMetaDataProvider {
@Override
public void initializeWithProcedureColumnMetaData(DatabaseMetaData databaseMetaData, @Nullable String catalogName,
@Nullable String schemaName, String procedureName) throws SQLException {
@Nullable String schemaName, @Nullable String procedureName) throws SQLException {
this.procedureColumnMetaDataUsed = true;
processProcedureColumns(databaseMetaData, catalogName, schemaName, procedureName);

View File

@ -71,12 +71,14 @@ public abstract class AbstractJdbcCall {
private volatile boolean compiled = false;
/** The generated string used for call statement */
@Nullable
private String callString;
/**
* A delegate enabling us to create CallableStatementCreators
* efficiently, based on this class's declared parameters.
*/
@Nullable
private CallableStatementCreatorFactory callableStatementFactory;
@ -222,6 +224,7 @@ public abstract class AbstractJdbcCall {
/**
* Get the call string that should be used based on parameters and meta data.
*/
@Nullable
public String getCallString() {
return this.callString;
}
@ -230,6 +233,7 @@ public abstract class AbstractJdbcCall {
* Get the {@link CallableStatementCreatorFactory} being used
*/
protected CallableStatementCreatorFactory getCallableStatementFactory() {
Assert.state(this.callableStatementFactory != null, "No CallableStatementCreatorFactory available");
return this.callableStatementFactory;
}
@ -322,7 +326,7 @@ public abstract class AbstractJdbcCall {
}
this.callableStatementFactory =
new CallableStatementCreatorFactory(getCallString(), this.callMetaDataContext.getCallParameters());
new CallableStatementCreatorFactory(this.callString, this.callMetaDataContext.getCallParameters());
onCompileInternal();
}

View File

@ -81,9 +81,11 @@ public abstract class AbstractJdbcInsert {
private volatile boolean compiled = false;
/** The generated string used for insert statement */
@Nullable
private String insertString;
/** The SQL type information for the insert columns */
@Nullable
private int[] insertTypes;
@ -222,6 +224,7 @@ public abstract class AbstractJdbcInsert {
/**
* Get the insert string to be used.
*/
@Nullable
public String getInsertString() {
return this.insertString;
}
@ -229,6 +232,7 @@ public abstract class AbstractJdbcInsert {
/**
* Get the array of {@link java.sql.Types} to be used for insert.
*/
@Nullable
public int[] getInsertTypes() {
return this.insertTypes;
}
@ -276,7 +280,7 @@ public abstract class AbstractJdbcInsert {
this.insertString = this.tableMetaDataContext.createInsertString(getGeneratedKeyNames());
this.insertTypes = this.tableMetaDataContext.createInsertTypes();
if (logger.isDebugEnabled()) {
logger.debug("Compiled insert object: insert string is [" + getInsertString() + "]");
logger.debug("Compiled insert object: insert string is [" + this.insertString + "]");
}
onCompileInternal();
}

View File

@ -22,6 +22,7 @@ import javax.sql.DataSource;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
@ -45,6 +46,7 @@ public class JdbcBeanDefinitionReader {
private final PropertiesBeanDefinitionReader propReader;
@Nullable
private JdbcTemplate jdbcTemplate;

View File

@ -126,7 +126,7 @@ public class IsolationLevelDataSourceAdapter extends UserCredentialsDataSourceAd
* @see #getCurrentReadOnlyFlag()
*/
@Override
protected Connection doGetConnection(String username, String password) throws SQLException {
protected Connection doGetConnection(@Nullable String username, @Nullable String password) throws SQLException {
Connection con = super.doGetConnection(username, password);
Boolean readOnlyToUse = getCurrentReadOnlyFlag();
if (readOnlyToUse != null) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -22,6 +22,7 @@ import java.sql.SQLException;
import java.util.Properties;
import org.springframework.beans.BeanUtils;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
@ -52,6 +53,7 @@ import org.springframework.util.Assert;
*/
public class SimpleDriverDataSource extends AbstractDriverBasedDataSource {
@Nullable
private Driver driver;
@ -117,13 +119,14 @@ public class SimpleDriverDataSource extends AbstractDriverBasedDataSource {
* Driver instance.
* @see #setDriverClass
*/
public void setDriver(Driver driver) {
public void setDriver(@Nullable Driver driver) {
this.driver = driver;
}
/**
* Return the JDBC Driver instance to use.
*/
@Nullable
public Driver getDriver() {
return this.driver;
}

View File

@ -132,7 +132,7 @@ public class WebSphereDataSourceAdapter extends IsolationLevelDataSourceAdapter
* @see com.ibm.websphere.rsadapter.WSDataSource#getConnection(com.ibm.websphere.rsadapter.JDBCConnectionSpec)
*/
@Override
protected Connection doGetConnection(String username, String password) throws SQLException {
protected Connection doGetConnection(@Nullable String username, @Nullable String password) throws SQLException {
// Create JDBCConnectionSpec using current isolation level value and read-only flag.
Object connSpec = createConnectionSpec(
getCurrentIsolationLevel(), getCurrentReadOnlyFlag(), username, password);

View File

@ -38,8 +38,10 @@ public class DataSourceInitializer implements InitializingBean, DisposableBean {
@Nullable
private DataSource dataSource;
@Nullable
private DatabasePopulator databasePopulator;
@Nullable
private DatabasePopulator databaseCleaner;
private boolean enabled = true;

View File

@ -171,6 +171,7 @@ public class Jdbc4SqlXmlHandler implements SqlXmlHandler {
*/
private static abstract class AbstractJdbc4SqlXmlValue implements SqlXmlValue {
@Nullable
private SQLXML xmlObject;
@Override
@ -187,11 +188,13 @@ public class Jdbc4SqlXmlHandler implements SqlXmlHandler {
@Override
public void cleanup() {
try {
this.xmlObject.free();
}
catch (SQLException ex) {
throw new DataAccessResourceFailureException("Could not free SQLXML object", ex);
if (this.xmlObject != null) {
try {
this.xmlObject.free();
}
catch (SQLException ex) {
throw new DataAccessResourceFailureException("Could not free SQLXML object", ex);
}
}
}

View File

@ -31,7 +31,6 @@ import org.springframework.jms.support.JmsUtils;
import org.springframework.jms.support.QosSettings;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ErrorHandler;
/**
@ -506,6 +505,7 @@ public abstract class AbstractMessageListenerContainer extends AbstractJmsListen
}
@Override
@Nullable
public QosSettings getReplyQosSettings() {
return this.replyQosSettings;
}
@ -514,11 +514,12 @@ public abstract class AbstractMessageListenerContainer extends AbstractJmsListen
* Set the {@link MessageConverter} strategy for converting JMS Messages.
* @since 4.1
*/
public void setMessageConverter(MessageConverter messageConverter) {
public void setMessageConverter(@Nullable MessageConverter messageConverter) {
this.messageConverter = messageConverter;
}
@Override
@Nullable
public MessageConverter getMessageConverter() {
return this.messageConverter;
}

View File

@ -144,7 +144,8 @@ public class MessageListenerAdapter extends AbstractAdaptableMessageListener imp
* @param delegate the delegate object
*/
public MessageListenerAdapter(Object delegate) {
setDelegate(delegate);
Assert.notNull(delegate, "Delegate must not be null");
this.delegate = delegate;
}
@ -196,12 +197,13 @@ public class MessageListenerAdapter extends AbstractAdaptableMessageListener imp
*/
@Override
@SuppressWarnings("unchecked")
public void onMessage(Message message, Session session) throws JMSException {
public void onMessage(Message message, @Nullable Session session) throws JMSException {
// Check whether the delegate is a MessageListener impl itself.
// In that case, the adapter will simply act as a pass-through.
Object delegate = getDelegate();
if (delegate != this) {
if (delegate instanceof SessionAwareMessageListener) {
Assert.state(session != null, "Session is required for SessionAwareMessageListener");
((SessionAwareMessageListener<Message>) delegate).onMessage(message, session);
return;
}

View File

@ -28,6 +28,7 @@ import org.springframework.messaging.MessagingException;
import org.springframework.messaging.core.AbstractMessageSendingTemplate;
import org.springframework.messaging.handler.invocation.InvocableHandlerMethod;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.util.Assert;
/**
* A {@link javax.jms.MessageListener} adapter that invokes a configurable
@ -49,6 +50,7 @@ import org.springframework.messaging.support.MessageBuilder;
*/
public class MessagingMessageListenerAdapter extends AbstractAdaptableMessageListener {
@Nullable
private InvocableHandlerMethod handlerMethod;
@ -60,9 +62,14 @@ public class MessagingMessageListenerAdapter extends AbstractAdaptableMessageLis
this.handlerMethod = handlerMethod;
}
private InvocableHandlerMethod getHandlerMethod() {
Assert.state(this.handlerMethod != null, "No HandlerMethod set");
return this.handlerMethod;
}
@Override
public void onMessage(javax.jms.Message jmsMessage, Session session) throws JMSException {
public void onMessage(javax.jms.Message jmsMessage, @Nullable Session session) throws JMSException {
Message<?> message = toMessagingMessage(jmsMessage);
if (logger.isDebugEnabled()) {
logger.debug("Processing [" + message + "]");
@ -78,7 +85,7 @@ public class MessagingMessageListenerAdapter extends AbstractAdaptableMessageLis
@Override
protected Object preProcessResponse(Object result) {
MethodParameter returnType = this.handlerMethod.getReturnType();
MethodParameter returnType = getHandlerMethod().getReturnType();
if (result instanceof Message) {
return MessageBuilder.fromMessage((Message<?>) result)
.setHeader(AbstractMessageSendingTemplate.CONVERSION_HINT_HEADER, returnType).build();
@ -101,9 +108,10 @@ public class MessagingMessageListenerAdapter extends AbstractAdaptableMessageLis
* with a dedicated error message.
*/
@Nullable
private Object invokeHandler(javax.jms.Message jmsMessage, Session session, Message<?> message) {
private Object invokeHandler(javax.jms.Message jmsMessage, @Nullable Session session, Message<?> message) {
InvocableHandlerMethod handlerMethod = getHandlerMethod();
try {
return this.handlerMethod.invoke(message, jmsMessage, session);
return handlerMethod.invoke(message, jmsMessage, session);
}
catch (MessagingException ex) {
throw new ListenerExecutionFailedException(
@ -111,15 +119,16 @@ public class MessagingMessageListenerAdapter extends AbstractAdaptableMessageLis
}
catch (Exception ex) {
throw new ListenerExecutionFailedException("Listener method '" +
this.handlerMethod.getMethod().toGenericString() + "' threw exception", ex);
handlerMethod.getMethod().toGenericString() + "' threw exception", ex);
}
}
private String createMessagingErrorMessage(String description) {
InvocableHandlerMethod handlerMethod = getHandlerMethod();
StringBuilder sb = new StringBuilder(description).append("\n")
.append("Endpoint handler details:\n")
.append("Method [").append(this.handlerMethod.getMethod()).append("]\n")
.append("Bean [").append(this.handlerMethod.getBean()).append("]\n");
.append("Method [").append(handlerMethod.getMethod()).append("]\n")
.append("Bean [").append(handlerMethod.getBean()).append("]\n");
return sb.toString();
}

View File

@ -22,6 +22,8 @@ import javax.resource.ResourceException;
import javax.resource.spi.UnavailableException;
import org.springframework.jca.endpoint.AbstractMessageEndpointFactory;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* JMS-specific implementation of the JCA 1.7
@ -47,6 +49,7 @@ import org.springframework.jca.endpoint.AbstractMessageEndpointFactory;
*/
public class JmsMessageEndpointFactory extends AbstractMessageEndpointFactory {
@Nullable
private MessageListener messageListener;
@ -61,6 +64,7 @@ public class JmsMessageEndpointFactory extends AbstractMessageEndpointFactory {
* Return the JMS MessageListener for this endpoint.
*/
protected MessageListener getMessageListener() {
Assert.state(messageListener != null, "No MessageListener set");
return this.messageListener;
}
@ -90,16 +94,12 @@ public class JmsMessageEndpointFactory extends AbstractMessageEndpointFactory {
}
}
try {
messageListener.onMessage(message);
getMessageListener().onMessage(message);
}
catch (RuntimeException ex) {
catch (RuntimeException | Error ex) {
onEndpointException(ex);
throw ex;
}
catch (Error err) {
onEndpointException(err);
throw err;
}
finally {
if (applyDeliveryCalls) {
try {
@ -114,7 +114,7 @@ public class JmsMessageEndpointFactory extends AbstractMessageEndpointFactory {
@Override
protected ClassLoader getEndpointClassLoader() {
return messageListener.getClass().getClassLoader();
return getMessageListener().getClass().getClassLoader();
}
}

View File

@ -59,6 +59,7 @@ public class JmsInvokerServiceExporter extends RemoteInvocationBasedExporter
private boolean ignoreInvalidRequests = true;
@Nullable
private Object proxy;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -32,6 +32,7 @@ import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.lang.Nullable;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.XmlMappingException;
@ -51,8 +52,10 @@ import org.springframework.util.Assert;
*/
public class MarshallingMessageConverter implements MessageConverter, InitializingBean {
@Nullable
private Marshaller marshaller;
@Nullable
private Unmarshaller unmarshaller;
private MessageType targetType = MessageType.BYTES;
@ -108,6 +111,7 @@ public class MarshallingMessageConverter implements MessageConverter, Initializi
* Set the {@link Marshaller} to be used by this message converter.
*/
public void setMarshaller(Marshaller marshaller) {
Assert.notNull(marshaller, "Marshaller must not be null");
this.marshaller = marshaller;
}
@ -115,6 +119,7 @@ public class MarshallingMessageConverter implements MessageConverter, Initializi
* Set the {@link Unmarshaller} to be used by this message converter.
*/
public void setUnmarshaller(Unmarshaller unmarshaller) {
Assert.notNull(unmarshaller, "Unmarshaller must not be null");
this.unmarshaller = unmarshaller;
}
@ -148,6 +153,7 @@ public class MarshallingMessageConverter implements MessageConverter, Initializi
*/
@Override
public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException {
Assert.state(this.marshaller != null, "No Marshaller set");
try {
switch (this.targetType) {
case TEXT:
@ -158,10 +164,7 @@ public class MarshallingMessageConverter implements MessageConverter, Initializi
return marshalToMessage(object, session, this.marshaller, this.targetType);
}
}
catch (XmlMappingException ex) {
throw new MessageConversionException("Could not marshal [" + object + "]", ex);
}
catch (IOException ex) {
catch (XmlMappingException | IOException ex) {
throw new MessageConversionException("Could not marshal [" + object + "]", ex);
}
}
@ -173,6 +176,7 @@ public class MarshallingMessageConverter implements MessageConverter, Initializi
*/
@Override
public Object fromMessage(Message message) throws JMSException, MessageConversionException {
Assert.state(this.unmarshaller != null, "No Unmarshaller set");
try {
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;

View File

@ -32,6 +32,7 @@ import org.springframework.util.MimeType;
*/
public class DefaultContentTypeResolver implements ContentTypeResolver {
@Nullable
private MimeType defaultMimeType;
@ -40,7 +41,7 @@ public class DefaultContentTypeResolver implements ContentTypeResolver {
* {@link MessageHeaders#CONTENT_TYPE} header present.
* <p>This property does not have a default value.
*/
public void setDefaultMimeType(MimeType defaultMimeType) {
public void setDefaultMimeType(@Nullable MimeType defaultMimeType) {
this.defaultMimeType = defaultMimeType;
}
@ -48,6 +49,7 @@ public class DefaultContentTypeResolver implements ContentTypeResolver {
* Return the default MIME type to use if no
* {@link MessageHeaders#CONTENT_TYPE} header is present.
*/
@Nullable
public MimeType getDefaultMimeType() {
return this.defaultMimeType;
}

View File

@ -276,6 +276,7 @@ public class GenericMessagingTemplate extends AbstractDestinationResolvingMessag
private final boolean throwExceptionOnLateReply;
@Nullable
private volatile Message<?> replyMessage;
private volatile boolean hasReceived;

View File

@ -283,7 +283,9 @@ public abstract class AbstractBrokerMessageHandler
private class UnsentDisconnectChannelInterceptor extends ChannelInterceptorAdapter {
@Override
public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) {
public void afterSendCompletion(
Message<?> message, MessageChannel channel, boolean sent, @Nullable Exception ex) {
if (!sent) {
SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(message.getHeaders());
if (SimpMessageType.DISCONNECT.equals(messageType)) {

View File

@ -548,6 +548,7 @@ public class DefaultStompSession implements ConnectionHandlingStompSession {
}
@Override
@Nullable
public String getReceiptId() {
return this.receiptId;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -256,7 +256,7 @@ public class StompHeaderAccessor extends SimpMessageHeaderAccessor {
}
@Override
public void setDestination(String destination) {
public void setDestination(@Nullable String destination) {
super.setDestination(destination);
setNativeHeader(STOMP_DESTINATION_HEADER, destination);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -18,6 +18,7 @@ package org.springframework.messaging.simp.user;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
@ -195,9 +196,9 @@ public class MultiServerUserRegistry implements SimpUserRegistry, SmartApplicati
*/
private static class UserRegistrySnapshot {
private String id;
private String id = "";
private Map<String, TransferSimpUser> users;
private Map<String, TransferSimpUser> users = Collections.emptyMap();
private long expirationTime;
@ -273,12 +274,12 @@ public class MultiServerUserRegistry implements SimpUserRegistry, SmartApplicati
*/
private static class TransferSimpUser implements SimpUser {
private String name;
private String name = "";
/* User sessions from "this" registry only (i.e. one server) */
// User sessions from "this" registry only (i.e. one server)
private Set<TransferSimpSession> sessions;
/* Cross-server session lookup (e.g. user connected to multiple servers) */
// Cross-server session lookup (e.g. user connected to multiple servers)
@Nullable
private SessionLookup sessionLookup;
@ -393,6 +394,8 @@ public class MultiServerUserRegistry implements SimpUserRegistry, SmartApplicati
*/
@SuppressWarnings("unused")
public TransferSimpSession() {
this.id = "";
this.user = new TransferSimpUser();
this.subscriptions = new HashSet<>(4);
}
@ -401,6 +404,7 @@ public class MultiServerUserRegistry implements SimpUserRegistry, SmartApplicati
*/
public TransferSimpSession(SimpSession session) {
this.id = session.getId();
this.user = new TransferSimpUser();
Set<SimpSubscription> subscriptions = session.getSubscriptions();
this.subscriptions = new HashSet<>(subscriptions.size());
for (SimpSubscription subscription : subscriptions) {
@ -443,12 +447,12 @@ public class MultiServerUserRegistry implements SimpUserRegistry, SmartApplicati
@Override
public boolean equals(Object other) {
return (this == other || (other instanceof SimpSession && this.id.equals(((SimpSession) other).getId())));
return (this == other || (other instanceof SimpSession && getId().equals(((SimpSession) other).getId())));
}
@Override
public int hashCode() {
return this.id.hashCode();
return getId().hashCode();
}
@Override
@ -474,6 +478,9 @@ public class MultiServerUserRegistry implements SimpUserRegistry, SmartApplicati
*/
@SuppressWarnings("unused")
public TransferSimpSubscription() {
this.id = "";
this.session = new TransferSimpSession();
this.destination = "";
}
/**
@ -481,6 +488,7 @@ public class MultiServerUserRegistry implements SimpUserRegistry, SmartApplicati
*/
public TransferSimpSubscription(SimpSubscription subscription) {
this.id = subscription.getId();
this.session = new TransferSimpSession();
this.destination = subscription.getDestination();
}
@ -520,13 +528,13 @@ public class MultiServerUserRegistry implements SimpUserRegistry, SmartApplicati
return false;
}
SimpSubscription otherSubscription = (SimpSubscription) other;
return (ObjectUtils.nullSafeEquals(getSession(), otherSubscription.getSession()) &&
this.id.equals(otherSubscription.getId()));
return (getId().equals(otherSubscription.getId()) &&
ObjectUtils.nullSafeEquals(getSession(), otherSubscription.getSession()));
}
@Override
public int hashCode() {
return this.id.hashCode() * 31 + ObjectUtils.nullSafeHashCode(getSession());
return getId().hashCode() * 31 + ObjectUtils.nullSafeHashCode(getSession());
}
@Override

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -18,6 +18,8 @@ package org.springframework.messaging.simp.user;
import java.util.Set;
import org.springframework.lang.Nullable;
/**
* Represents a session of connected user.
*

View File

@ -16,6 +16,8 @@
package org.springframework.messaging.simp.user;
import org.springframework.lang.Nullable;
/**
* Represents a subscription within a user session.
*
@ -25,17 +27,17 @@ package org.springframework.messaging.simp.user;
public interface SimpSubscription {
/**
* Return the id associated of the subscription (never {@code null}).
* Return the id associated of the subscription.
*/
String getId();
/**
* Return the session of the subscription (never {@code null}).
* Return the session of the subscription.
*/
SimpSession getSession();
/**
* Return the subscription's destination (never {@code null}).
* Return the subscription's destination.
*/
String getDestination();

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,6 +16,7 @@
package org.springframework.messaging.support;
import org.springframework.lang.Nullable;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
@ -39,7 +40,7 @@ public abstract class ChannelInterceptorAdapter implements ChannelInterceptor {
}
@Override
public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) {
public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, @Nullable Exception ex) {
}
public boolean preReceive(MessageChannel channel) {
@ -52,7 +53,7 @@ public abstract class ChannelInterceptorAdapter implements ChannelInterceptor {
}
@Override
public void afterReceiveCompletion(Message<?> message, MessageChannel channel, Exception ex) {
public void afterReceiveCompletion(@Nullable Message<?> message, MessageChannel channel, @Nullable Exception ex) {
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -49,7 +49,7 @@ public class MultiServerUserRegistryTests {
@Before
public void setUp() throws Exception {
public void setup() throws Exception {
this.localRegistry = Mockito.mock(SimpUserRegistry.class);
this.registry = new MultiServerUserRegistry(this.localRegistry);
this.converter = new MappingJackson2MessageConverter();
@ -70,7 +70,6 @@ public class MultiServerUserRegistryTests {
@Test
public void getUserFromRemoteRegistry() throws Exception {
// Prepare broadcast message from remote server
TestSimpUser testUser = new TestSimpUser("joe");
TestSimpSession testSession = new TestSimpSession("remote-sess");
@ -84,7 +83,6 @@ public class MultiServerUserRegistryTests {
// Add remote registry
this.registry.addRemoteRegistryDto(message, this.converter, 20000);
assertEquals(1, this.registry.getUserCount());
SimpUser user = this.registry.getUser("joe");
assertNotNull(user);
@ -103,7 +101,6 @@ public class MultiServerUserRegistryTests {
@Test
public void findSubscriptionsFromRemoteRegistry() throws Exception {
// Prepare broadcast message from remote server
TestSimpUser user1 = new TestSimpUser("joe");
TestSimpUser user2 = new TestSimpUser("jane");
@ -125,7 +122,6 @@ public class MultiServerUserRegistryTests {
// Add remote registry
this.registry.addRemoteRegistryDto(message, this.converter, 20000);
assertEquals(3, this.registry.getUserCount());
Set<SimpSubscription> matches = this.registry.findSubscriptions(s -> s.getDestination().equals("/match"));
assertEquals(2, matches.size());
@ -136,9 +132,8 @@ public class MultiServerUserRegistryTests {
assertEquals(new HashSet<>(Arrays.asList("sess1", "sess2")), sessionIds);
}
@Test // SPR-13800
@Test // SPR-13800
public void getSessionsWhenUserIsConnectedToMultipleServers() throws Exception {
// Add user to local registry
TestSimpUser localUser = new TestSimpUser("joe");
TestSimpSession localSession = new TestSimpSession("sess123");
@ -175,7 +170,6 @@ public class MultiServerUserRegistryTests {
@Test
public void purgeExpiredRegistries() throws Exception {
// Prepare broadcast message from remote server
TestSimpUser testUser = new TestSimpUser("joe");
testUser.addSessions(new TestSimpSession("remote-sub"));

View File

@ -30,6 +30,7 @@ import org.springframework.orm.hibernate5.SessionFactoryUtils;
import org.springframework.orm.hibernate5.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.web.context.request.AsyncWebRequestInterceptor;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.request.async.CallableProcessingInterceptor;
@ -79,23 +80,31 @@ public class OpenSessionInViewInterceptor implements AsyncWebRequestInterceptor
protected final Log logger = LogFactory.getLog(getClass());
@Nullable
private SessionFactory sessionFactory;
/**
* Set the Hibernate SessionFactory that should be used to create Hibernate Sessions.
*/
public void setSessionFactory(SessionFactory sessionFactory) {
public void setSessionFactory(@Nullable SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
/**
* Return the Hibernate SessionFactory that should be used to create Hibernate Sessions.
*/
@Nullable
public SessionFactory getSessionFactory() {
return this.sessionFactory;
}
private SessionFactory obtainSessionFactory() {
SessionFactory sf = getSessionFactory();
Assert.state(sf != null, "No SessionFactory set");
return sf;
}
/**
* Open a new Hibernate {@code Session} according and bind it to the thread via the
@ -112,7 +121,7 @@ public class OpenSessionInViewInterceptor implements AsyncWebRequestInterceptor
}
}
if (TransactionSynchronizationManager.hasResource(getSessionFactory())) {
if (TransactionSynchronizationManager.hasResource(obtainSessionFactory())) {
// Do not modify the Session: just mark the request accordingly.
Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
int newCount = (count != null ? count + 1 : 1);
@ -122,10 +131,10 @@ public class OpenSessionInViewInterceptor implements AsyncWebRequestInterceptor
logger.debug("Opening Hibernate Session in OpenSessionInViewInterceptor");
Session session = openSession();
SessionHolder sessionHolder = new SessionHolder(session);
TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder);
TransactionSynchronizationManager.bindResource(obtainSessionFactory(), sessionHolder);
AsyncRequestInterceptor asyncRequestInterceptor =
new AsyncRequestInterceptor(getSessionFactory(), sessionHolder);
new AsyncRequestInterceptor(obtainSessionFactory(), sessionHolder);
asyncManager.registerCallableInterceptor(participateAttributeName, asyncRequestInterceptor);
asyncManager.registerDeferredResultInterceptor(participateAttributeName, asyncRequestInterceptor);
}
@ -143,7 +152,7 @@ public class OpenSessionInViewInterceptor implements AsyncWebRequestInterceptor
public void afterCompletion(WebRequest request, @Nullable Exception ex) throws DataAccessException {
if (!decrementParticipateCount(request)) {
SessionHolder sessionHolder =
(SessionHolder) TransactionSynchronizationManager.unbindResource(getSessionFactory());
(SessionHolder) TransactionSynchronizationManager.unbindResource(obtainSessionFactory());
logger.debug("Closing Hibernate Session in OpenSessionInViewInterceptor");
SessionFactoryUtils.closeSession(sessionHolder.getSession());
}
@ -168,7 +177,7 @@ public class OpenSessionInViewInterceptor implements AsyncWebRequestInterceptor
@Override
public void afterConcurrentHandlingStarted(WebRequest request) {
if (!decrementParticipateCount(request)) {
TransactionSynchronizationManager.unbindResource(getSessionFactory());
TransactionSynchronizationManager.unbindResource(obtainSessionFactory());
}
}
@ -183,7 +192,7 @@ public class OpenSessionInViewInterceptor implements AsyncWebRequestInterceptor
@SuppressWarnings("deprecation")
protected Session openSession() throws DataAccessResourceFailureException {
try {
Session session = getSessionFactory().openSession();
Session session = obtainSessionFactory().openSession();
session.setFlushMode(FlushMode.MANUAL);
return session;
}
@ -199,7 +208,7 @@ public class OpenSessionInViewInterceptor implements AsyncWebRequestInterceptor
* of the {@code SessionFactory} instance and appends {@link #PARTICIPATE_SUFFIX}.
*/
protected String getParticipateAttributeName() {
return getSessionFactory().toString() + PARTICIPATE_SUFFIX;
return obtainSessionFactory().toString() + PARTICIPATE_SUFFIX;
}
private boolean applySessionBindingInterceptor(WebAsyncManager asyncManager, String key) {

Some files were not shown because too many files have changed in this diff Show More