Formatting pass, primarily to align with Spring's convention of hard tab indentation.

This commit is contained in:
Chris Beams 2009-02-28 06:18:46 +00:00
parent f8270428df
commit f9918f9b2e
42 changed files with 3002 additions and 2788 deletions

View File

@ -29,31 +29,36 @@ import org.springframework.stereotype.Component;
/**
* Annotation indicating that a class is a "Java Configuration" class, meaning that it exposes one
* or more {@link Bean} methods. Holds similar information to that held in the default values of a
* bean factory; can generally be thought of as the JavaConfig equivalent of XML's 'beans' root
* element.
* Annotation indicating that a class is a "Java Configuration" class, meaning that it
* exposes one or more {@link Bean} methods. Holds similar information to that held in the
* default values of a bean factory; can generally be thought of as the JavaConfig
* equivalent of XML's 'beans' root element.
*
* <p>Note however that the information here is not used to populate the defaults of the owning bean
* factory, which would affect other configurations. In the style of the Java configuration
* mechanism generally, each Java configuration class is kept isolated.</p>
* <p>
* Note however that the information here is not used to populate the defaults of the owning
* bean factory, which would affect other configurations. In the style of the Java
* configuration mechanism generally, each Java configuration class is kept isolated.
* </p>
*
* <p>Configuration-annotated classes are also candidates for component scanning thanks to the fact
* that this annotation is meta-annotated with {@link Component @Component}.</p>
* <p>
* Configuration-annotated classes are also candidates for component scanning thanks to the
* fact that this annotation is meta-annotated with {@link Component @Component}.
* </p>
*
* @author Rod Johnson
* @author Chris Beams
*/
@Component
@Target({ ElementType.TYPE })
@Target( { ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Configuration {
/**
* Configuration name. Allow different variants, such as test, production
* etc. Default will always match.
* Configuration name. Allow different variants, such as test, production etc. Default
* will always match.
*
* @return
*/
String[] names() default "";
@ -66,23 +71,23 @@ public @interface Configuration {
*/
Autowire defaultAutowire() default Autowire.INHERITED;
// /**
// * Dependency check strategy. By default, the dependency check is
// * unspecified, that is the default Spring option will apply. In most cases,
// * it means no dependency check will be done.
// *
// * @see DependencyCheck
// * @return
// */
// DependencyCheck defaultDependencyCheck() default DependencyCheck.UNSPECIFIED;
//
// /**
// * Bean instantiation strategy. By default, it is unspecified.
// *
// * @see Lazy
// * @return
// */
// Lazy defaultLazy() default Lazy.UNSPECIFIED;
// /**
// * Dependency check strategy. By default, the dependency check is
// * unspecified, that is the default Spring option will apply. In most cases,
// * it means no dependency check will be done.
// *
// * @see DependencyCheck
// * @return
// */
// DependencyCheck defaultDependencyCheck() default DependencyCheck.UNSPECIFIED;
//
// /**
// * Bean instantiation strategy. By default, it is unspecified.
// *
// * @see Lazy
// * @return
// */
// Lazy defaultLazy() default Lazy.UNSPECIFIED;
/**
* Do we autowire with aspects from the enclosing factory scope?
@ -90,8 +95,7 @@ public @interface Configuration {
boolean useFactoryAspects() default false;
/**
* Do we check {@link Required @Required} methods to make sure they've been
* called?
* Do we check {@link Required @Required} methods to make sure they've been called?
*/
boolean checkRequired() default false;

View File

@ -30,15 +30,18 @@ import sun.security.x509.Extension;
/**
* Abstract representation of a user-defined {@link Configuration @Configuration} class. Includes a
* set of Bean methods, AutoBean methods, ExternalBean methods, ExternalValue methods, etc. Includes
* all such methods defined in the ancestry of the class, in a 'flattened-out' manner. Note that
* each BeanMethod representation does still contain source information about where it was
* originally detected (for the purpose of tooling with Spring IDE).
* Abstract representation of a user-defined {@link Configuration @Configuration} class.
* Includes a set of Bean methods, AutoBean methods, ExternalBean methods, ExternalValue
* methods, etc. Includes all such methods defined in the ancestry of the class, in a
* 'flattened-out' manner. Note that each BeanMethod representation does still contain
* source information about where it was originally detected (for the purpose of tooling
* with Spring IDE).
*
* <p>Like the rest of the {@link org.springframework.config.java.model model} package,
* this class follows the fluent interface / builder pattern such that a model can be built up
* easily by method chaining.</p>
* <p>
* Like the rest of the {@link org.springframework.config.java.model model} package, this
* class follows the fluent interface / builder pattern such that a model can be built up
* easily by method chaining.
* </p>
*
* @author Chris Beams
*/
@ -58,7 +61,8 @@ public final class ConfigurationClass extends ModelClass implements Validatable
private ConfigurationClass declaringClass;
public ConfigurationClass() { }
public ConfigurationClass() {
}
// TODO: get rid of constructors used only for testing. put in testing util.
/**
@ -81,7 +85,9 @@ public final class ConfigurationClass extends ModelClass implements Validatable
}
private static Configuration defaultAnnotation() {
@Configuration class Prototype { }
@Configuration
class Prototype {
}
return Prototype.class.getAnnotation(Configuration.class);
}
@ -89,12 +95,12 @@ public final class ConfigurationClass extends ModelClass implements Validatable
* Creates a new ConfigurationClass object.
*
* @param name Fully qualified name of the class being represented
* @param id Bean name/id (if any) of this configuration class. used only in the case
* of XML integration where {@link Configuration} beans may have a
* user-specified id.
* @param metadata Configuration annotation resident on this class. May be null indicating
* that the user specified this class to be processed but failed to properly
* annotate it.
* @param id Bean name/id (if any) of this configuration class. used only in the case of
* XML integration where {@link Configuration} beans may have a user-specified
* id.
* @param metadata Configuration annotation resident on this class. May be null
* indicating that the user specified this class to be processed but failed to
* properly annotate it.
* @param modifiers Per {@link java.lang.reflect.Modifier}
*/
public ConfigurationClass(String name, String id, Configuration metadata, int modifiers) {
@ -178,15 +184,14 @@ public final class ConfigurationClass extends ModelClass implements Validatable
if (Modifier.isFinal(modifiers))
errors.add(new FinalConfigurationError());
for(ModelMethod method : methods)
for (ModelMethod method : methods)
method.validate(errors);
}
@Override
public String toString() {
return format("%s; modifiers=%d; methods=%s",
super.toString(), modifiers, methods);
return format("%s; modifiers=%d; methods=%s", super.toString(), modifiers, methods);
}
@Override
@ -251,8 +256,8 @@ public final class ConfigurationClass extends ModelClass implements Validatable
@Override
public String getDescription() {
return format("%s was provided as a Java Configuration class but was not annotated with @%s. "
+ "Update the class definition to continue.",
getSimpleName(), Configuration.class.getSimpleName());
+ "Update the class definition to continue.", getSimpleName(), Configuration.class
.getSimpleName());
}
}
@ -287,8 +292,8 @@ public final class ConfigurationClass extends ModelClass implements Validatable
}
/**
* Error raised when a Bean marked as 'allowOverriding=false' is attempted to be overridden by
* another bean definition.
* Error raised when a Bean marked as 'allowOverriding=false' is attempted to be
* overridden by another bean definition.
*
* @see Bean#allowOverriding()
*/
@ -300,13 +305,12 @@ public final class ConfigurationClass extends ModelClass implements Validatable
* Creates a new IllegalBeanOverrideError object.
*
* @param violatingClass class attempting an illegal override. null value signifies
* that the violating class is unknown or that there is no
* class to speak of (in the case of an XML bean definition
* doing the illegal overriding)
* @param finalMethodInQuestion the method that has been marked 'allowOverriding=false'
* that the violating class is unknown or that there is no class to speak of
* (in the case of an XML bean definition doing the illegal overriding)
* @param finalMethodInQuestion the method that has been marked
* 'allowOverriding=false'
*/
public IllegalBeanOverrideError(ConfigurationClass violatingClass,
ModelMethod finalMethodInQuestion) {
public IllegalBeanOverrideError(ConfigurationClass violatingClass, ModelMethod finalMethodInQuestion) {
super(violatingClass, -1);
this.authoritativeClass = ConfigurationClass.this;
this.finalMethodInQuestion = finalMethodInQuestion;
@ -327,8 +331,8 @@ public final class ConfigurationClass extends ModelClass implements Validatable
public ModelMethod getMethod(String methodName) {
for(ModelMethod method : methods)
if(methodName.equals(method.getName()))
for (ModelMethod method : methods)
if (methodName.equals(method.getName()))
return method;
return null;

View File

@ -21,17 +21,19 @@ import java.util.ArrayList;
import java.util.List;
/**
* An abstract representation of a set of user-provided "Configuration classes", usually but not
* necessarily annotated with {@link Configuration @Configuration}. The model is populated with a
* {@link org.springframework.config.java.internal.parsing.ConfigurationParser} implementation which
* may be reflection-based or ASM-based. Once a model has been populated, it can then be rendered
* out to a set of BeanDefinitions. The model provides an important layer of indirection between the
* complexity of parsing a set of classes and the complexity of representing the contents of those
* classes as BeanDefinitions.
* An abstract representation of a set of user-provided "Configuration classes", usually but
* not necessarily annotated with {@link Configuration @Configuration}. The model is
* populated with a
* {@link org.springframework.config.java.internal.parsing.ConfigurationParser}
* implementation which may be reflection-based or ASM-based. Once a model has been
* populated, it can then be rendered out to a set of BeanDefinitions. The model provides an
* important layer of indirection between the complexity of parsing a set of classes and the
* complexity of representing the contents of those classes as BeanDefinitions.
*
* <p>Interface follows the builder pattern for method chaining.</p>
* <p>
* Interface follows the builder pattern for method chaining.
* </p>
*
* @author Chris Beams
* @see org.springframework.config.java.internal.parsing.ConfigurationParser
@ -43,9 +45,9 @@ public final class ConfigurationModel implements Validatable {
private final ArrayList<Validator> validators = new ArrayList<Validator>();
/**
* Add a {@link Configuration @Configuration} class to the model. Classes may be added at will
* and without any particular validation. Malformed classes will be caught and errors processed
* during {@link #validate() validation}
* Add a {@link Configuration @Configuration} class to the model. Classes may be added
* at will and without any particular validation. Malformed classes will be caught and
* errors processed during {@link #validate() validation}
*
* @param configurationClass user-supplied Configuration class
*/
@ -64,30 +66,32 @@ public final class ConfigurationModel implements Validatable {
* @see #getAllConfigurationClasses()
*/
public ConfigurationClass[] getConfigurationClasses() {
return configurationClasses.toArray(new ConfigurationClass[] { });
return configurationClasses.toArray(new ConfigurationClass[] {});
}
// /**
// * Return all configuration classes, including all imported configuration classes. This method
// * should be generally preferred over {@link #getConfigurationClasses()}
// *
// * @see #getConfigurationClasses()
// */
// public ConfigurationClass[] getAllConfigurationClasses() {
// ArrayList<ConfigurationClass> allConfigClasses = new ArrayList<ConfigurationClass>();
//
// for (ConfigurationClass configClass : configurationClasses)
// allConfigClasses.addAll(configClass.getSelfAndAllImports());
//
// return allConfigClasses.toArray(new ConfigurationClass[allConfigClasses.size()]);
// }
// /**
// * Return all configuration classes, including all imported configuration classes.
// This method
// * should be generally preferred over {@link #getConfigurationClasses()}
// *
// * @see #getConfigurationClasses()
// */
// public ConfigurationClass[] getAllConfigurationClasses() {
// ArrayList<ConfigurationClass> allConfigClasses = new ArrayList<ConfigurationClass>();
//
// for (ConfigurationClass configClass : configurationClasses)
// allConfigClasses.addAll(configClass.getSelfAndAllImports());
//
// return allConfigClasses.toArray(new ConfigurationClass[allConfigClasses.size()]);
// }
public ConfigurationClass[] getAllConfigurationClasses() {
return configurationClasses.toArray(new ConfigurationClass[configurationClasses.size()]);
}
/**
* Recurses through the model validating each object along the way and aggregating any <var>errors</var>.
* Recurses through the model validating each object along the way and aggregating any
* <var>errors</var>.
*
* @see ConfigurationClass#validate(java.util.List)
* @see ModelMethod#validate(java.util.List)
@ -103,21 +107,21 @@ public final class ConfigurationModel implements Validatable {
// depending on where they are registered (with the model, the class, or the method)
// they will be called directly or indirectly below
for (ConfigurationClass configClass : getAllConfigurationClasses()) {
for(ModelMethod method : configClass.getMethods()) {
for(Validator validator : method.getValidators()) {
if(validator.supports(method))
for (ModelMethod method : configClass.getMethods()) {
for (Validator validator : method.getValidators()) {
if (validator.supports(method))
method.registerValidator(validator);
// TODO: support class-level validation
// if(validator.supports(configClass))
// configClass.registerValidator(validator);
if(validator.supports(this))
if (validator.supports(this))
this.registerValidator(validator);
}
}
}
// process any validators registered directly with this model object
for(Validator validator : validators)
for (Validator validator : validators)
validator.validate(this, errors);
// each individual configuration class must be well-formed
@ -129,8 +133,7 @@ public final class ConfigurationModel implements Validatable {
@Override
public String toString() {
return format("%s: configurationClasses=%s",
getClass().getSimpleName(), configurationClasses);
return format("%s: configurationClasses=%s", getClass().getSimpleName(), configurationClasses);
}
@Override

View File

@ -24,6 +24,7 @@ import java.lang.annotation.Target;
import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.NoOp;
/**
* Meta-annotation used to identify annotations as producers of beans and/or values.
*
@ -35,21 +36,20 @@ import net.sf.cglib.proxy.NoOp;
public @interface Factory {
/**
* Specifies which registrar (if any) should be used to register
* bean definitions for this {@link Factory} method.
* Specifies which registrar (if any) should be used to register bean definitions for
* this {@link Factory} method.
*/
Class<? extends BeanDefinitionRegistrar> registrarType();
/**
* Specifies what (if any) callback should be used when processing this {@link Factory} method.
* Defaults to CGLIB's {@link NoOp}, which does nothing.
* TODO: rename (interceptorType)? to keep with the -or|-ar nomenclature
* Specifies what (if any) callback should be used when processing this {@link Factory}
* method. Defaults to CGLIB's {@link NoOp}, which does nothing. TODO: rename
* (interceptorType)? to keep with the -or|-ar nomenclature
*/
Class<? extends Callback> callbackType() default NoOp.class;
/**
* TODO: document
* TODO: rename
* TODO: document TODO: rename
*/
Class<? extends Validator>[] validatorTypes() default {};
}

View File

@ -21,9 +21,8 @@ import org.springframework.util.ClassUtils;
/**
* Abstract representation of a class, free from java reflection.
* Base class used within the internal JavaConfig metamodel for
* representing {@link Configuration} classes.
* Abstract representation of a class, free from java reflection. Base class used within the
* internal JavaConfig metamodel for representing {@link Configuration} classes.
*
* @author Chris Beams
*/
@ -37,7 +36,8 @@ public class ModelClass implements BeanMetadataElement {
/**
* Creates a new and empty ModelClass instance.
*/
public ModelClass() { }
public ModelClass() {
}
/**
* Creates a new ModelClass instance
@ -95,8 +95,8 @@ public class ModelClass implements BeanMetadataElement {
}
/**
* Returns a resource path-formatted representation of the .java
* file that declares this class
* Returns a resource path-formatted representation of the .java file that declares this
* class
*/
public String getSource() {
return source;
@ -113,7 +113,9 @@ public class ModelClass implements BeanMetadataElement {
}
/**
* Given a ModelClass instance representing a class com.acme.Foo, this method will return
* Given a ModelClass instance representing a class com.acme.Foo, this method will
* return
*
* <pre>
* ModelClass: name=Foo
* </pre>

View File

@ -48,9 +48,9 @@ public final class ModelMethod implements Validatable {
this.name = name;
Assert.notNull(annotations);
for(Annotation annotation : annotations) {
for (Annotation annotation : annotations) {
this.annotations.add(annotation);
if(factoryAnno == null)
if (factoryAnno == null)
factoryAnno = annotation.annotationType().getAnnotation(Factory.class);
}
@ -84,8 +84,8 @@ public final class ModelMethod implements Validatable {
*/
@SuppressWarnings("unchecked")
public <T extends Annotation> T getAnnotation(Class<T> annoType) {
for(Annotation anno : annotations)
if(anno.annotationType().equals(annoType))
for (Annotation anno : annotations)
if (anno.annotationType().equals(annoType))
return (T) anno;
return null;
@ -100,9 +100,9 @@ public final class ModelMethod implements Validatable {
public <T extends Annotation> T getRequiredAnnotation(Class<T> annoType) {
T anno = getAnnotation(annoType);
if(anno == null)
throw new IllegalStateException(
format("annotation %s not found on %s", annoType.getSimpleName(), this));
if (anno == null)
throw new IllegalStateException(format("annotation %s not found on %s", annoType.getSimpleName(),
this));
return anno;
}
@ -133,7 +133,7 @@ public final class ModelMethod implements Validatable {
}
public void validate(List<UsageError> errors) {
for(Validator validator : validators)
for (Validator validator : validators)
validator.validate(this, errors);
if (Modifier.isPrivate(getModifiers()))
@ -150,7 +150,7 @@ public final class ModelMethod implements Validatable {
public Set<Validator> getValidators() {
HashSet<Validator> validator = new HashSet<Validator>();
for(Class<? extends Validator> validatorType : factoryAnno.validatorTypes())
for (Class<? extends Validator> validatorType : factoryAnno.validatorTypes())
validator.add(getInstance(validatorType));
return validator;
@ -159,7 +159,7 @@ public final class ModelMethod implements Validatable {
public Callback getCallback() {
Class<? extends Callback> callbackType = factoryAnno.callbackType();
if(callbackType.equals(NoOp.class))
if (callbackType.equals(NoOp.class))
return NoOp.INSTANCE;
return getInstance(callbackType);
@ -168,8 +168,8 @@ public final class ModelMethod implements Validatable {
@Override
public String toString() {
String returnTypeName = returnType == null ? "<unknown>" : returnType.getSimpleName();
return String.format("%s: name=%s; returnType=%s; modifiers=%d",
getClass().getSimpleName(), name, returnTypeName, modifiers);
return String.format("%s: name=%s; returnType=%s; modifiers=%d", getClass().getSimpleName(), name,
returnTypeName, modifiers);
}
@Override
@ -232,8 +232,7 @@ public final class ModelMethod implements Validatable {
@Override
public String getDescription() {
return format("method '%s' may not be final - remove the final modifier to continue",
getName());
return format("method '%s' may not be final - remove the final modifier to continue", getName());
}
}

View File

@ -19,23 +19,24 @@ package org.springframework.config.java;
/**
* Enumerates the names of the scopes supported out of the box in Spring.
* <p>
* Not modeled as an actual java enum because annotations that accept a scope
* attribute must allow for user-defined scope names. Given that java
* enums are not extensible, these must remain simple string constants.
* Not modeled as an actual java enum because annotations that accept a scope attribute must
* allow for user-defined scope names. Given that java enums are not extensible, these must
* remain simple string constants.
*
* @author Chris Beams
* @since 3.0
*/
public class Scopes {
private Scopes() { }
private Scopes() {
}
public static final String SINGLETON = "singleton"; // see BeanDefinition.SCOPE_SINGLETON;
public static final String SINGLETON = "singleton";
public static final String PROTOTYPE = "prototype"; // see BeanDefinition.SCOPE_PROTOTYPE;
public static final String PROTOTYPE = "prototype";
public static final String REQUEST = "request"; // see WebApplicationContext.SCOPE_REQUEST;
public static final String REQUEST = "request";
public static final String SESSION = "session"; // see WebApplicationContext.SCOPE_SESSION;
public static final String SESSION = "session";
}

View File

@ -16,12 +16,11 @@
package org.springframework.config.java;
/**
* Represents an invalid usage of JavaConfig constructs, e.g. a {@link Configuration} that declares
* no {@link Bean @Bean} methods, or declaring both {@link Bean @Bean} and
* {@link ExternalBean @ExternalBean} on a single method. Explore the type hierarchy to discover all
* possible usage errors.
* Represents an invalid usage of JavaConfig constructs, e.g. a {@link Configuration} that
* declares no {@link Bean @Bean} methods, or declaring both {@link Bean @Bean} and
* {@link ExternalBean @ExternalBean} on a single method. Explore the type hierarchy to
* discover all possible usage errors.
*
* @author Chris Beams
* @see MalformedConfigurationException
@ -34,9 +33,10 @@ public abstract class UsageError {
/**
* Create a new usage error, providing information about where the error was detected.
*
* @param modelClass class in which this error was detected. Null value indicates that the
* error was not local to a single class.
* @param lineNumber line number on which this error was detected (useful for tooling integration)
* @param modelClass class in which this error was detected. Null value indicates that
* the error was not local to a single class.
* @param lineNumber line number on which this error was detected (useful for tooling
* integration)
*
* @see ModelClass#getSource()
*/
@ -51,8 +51,9 @@ public abstract class UsageError {
public abstract String getDescription();
/**
* Same as {@link #getDescription()} but attributed with class and line number information. If
* modelClass constructor parameter was null, class and line number information will be omitted.
* Same as {@link #getDescription()} but attributed with class and line number
* information. If modelClass constructor parameter was null, class and line number
* information will be omitted.
*/
public final String getAttributedDescription() {
if (clazz == null)

View File

@ -14,6 +14,7 @@ import org.springframework.util.ReflectionUtils;
import sun.security.x509.Extension;
/**
* Misc utils
*
@ -27,11 +28,11 @@ public class Util {
private static final Log log = LogFactory.getLog(Util.class);
private Util() { }
private Util() {
}
/**
* Returns instance of type T by invoking its default or no-arg
* constructor.
* Returns instance of type T by invoking its default or no-arg constructor.
* <p>
* Any reflection-related issues are re-thrown as unchecked.
*/
@ -42,16 +43,16 @@ public class Util {
return noArgCtor.newInstance();
} catch (Exception ex) {
ReflectionUtils.handleReflectionException(ex);
throw new IllegalStateException(
format("Unexpected reflection exception - %s: %s",
ex.getClass().getName(), ex.getMessage()));
throw new IllegalStateException(format("Unexpected reflection exception - %s: %s", ex.getClass()
.getName(), ex.getMessage()));
}
}
/**
* Loads the specified class using the default class loader, gracefully handling any
* {@link ClassNotFoundException} that may be thrown. This functionality is specifically
* implemented to accomodate tooling (Spring IDE) concerns, where user-defined types will not be
* implemented to accomodate tooling (Spring IDE) concerns, where user-defined types
* will not be
*
* @param <T> type of class to be returned
* @param fqClassName fully-qualified class name
@ -89,34 +90,36 @@ public class Util {
@SuppressWarnings("unchecked")
public static <T> Class<? extends T> loadRequiredClass(String fqClassName) {
try {
return (Class<? extends T>)getDefaultClassLoader().loadClass(fqClassName);
return (Class<? extends T>) getDefaultClassLoader().loadClass(fqClassName);
} catch (ClassNotFoundException ex) {
throw new IllegalArgumentException(
format("Class [%s] could not be loaded, check your CLASSPATH.", fqClassName), ex);
throw new IllegalArgumentException(format(
"Class [%s] could not be loaded, check your CLASSPATH.", fqClassName), ex);
}
}
/**
* Loads the specified class using the default class loader, gracefully handling any
* {@link ClassNotFoundException} that may be thrown by issuing a WARN level logging statement
* and return null. This functionality is specifically implemented to accomodate tooling
* (Spring IDE) concerns, where user-defined types will not be available to the tooling.
* {@link ClassNotFoundException} that may be thrown by issuing a WARN level logging
* statement and return null. This functionality is specifically implemented to
* accomodate tooling (Spring IDE) concerns, where user-defined types will not be
* available to the tooling.
* <p>
* ASM class reading is used throughout JavaConfig, but there are certain cases where
* classloading cannot be avoided - specifically in cases where users define their own
* {@link Extension} or {@link Factory} annotations. This method should therefore be used sparingly
* but consistently where required.
* {@link Extension} or {@link Factory} annotations. This method should therefore be
* used sparingly but consistently where required.
* <p>
* Because {@link ClassNotFoundException} is compensated for by returning null, callers must
* take care to handle the null case appropriately.
* Because {@link ClassNotFoundException} is compensated for by returning null, callers
* must take care to handle the null case appropriately.
* <p>
* In cases where the WARN logging statement is not desired, use the {@link #loadClass(String)}
* method, which returns null but issues no logging statements.
* In cases where the WARN logging statement is not desired, use the
* {@link #loadClass(String)} method, which returns null but issues no logging
* statements.
* <p>
* This method should only ever return null in the case of a user-defined type be processed at
* tooling time. Therefore, tooling may not be able to represent any custom annotation
* semantics, but JavaConfig itself will not have any problem loading and respecting them at
* actual runtime.
* This method should only ever return null in the case of a user-defined type be
* processed at tooling time. Therefore, tooling may not be able to represent any custom
* annotation semantics, but JavaConfig itself will not have any problem loading and
* respecting them at actual runtime.
*
* @param <T> type of class to be returned
* @param fqClassName fully-qualified class name
@ -139,11 +142,11 @@ public class Util {
}
/**
* Uses the default ClassLoader to load <var>pathToClass</var>. Appends '.class'
* to pathToClass before attempting to load.
* Uses the default ClassLoader to load <var>pathToClass</var>. Appends '.class' to
* pathToClass before attempting to load.
*
* @param pathToClass resource path to class, not including .class suffix.
* e.g.: com/acme/MyClass
* @param pathToClass resource path to class, not including .class suffix. e.g.:
* com/acme/MyClass
*
* @return inputStream for <var>pathToClass</var>
*
@ -155,8 +158,8 @@ public class Util {
InputStream is = ClassUtils.getDefaultClassLoader().getResourceAsStream(classFileName);
if (is == null)
throw new RuntimeException(
new FileNotFoundException("Class file [" + classFileName + "] not found"));
throw new RuntimeException(new FileNotFoundException("Class file [" + classFileName
+ "] not found"));
return is;
}

View File

@ -2,6 +2,7 @@ package org.springframework.config.java;
import java.util.List;
/**
* Indicates a type is able to be validated for errors.
*

View File

@ -4,8 +4,8 @@ import java.util.List;
/** Marker interface */
//TODO: SJC-242 document
//TODO: SJC-242 rename
// TODO: SJC-242 document
// TODO: SJC-242 rename
public interface Validator {
boolean supports(Object object);

View File

@ -37,23 +37,29 @@ import org.springframework.config.java.Validator;
/**
* Annotation to be applied to methods that create beans in a Spring context. The name of the bean
* is the method name. (It is also possible to specify aliases using the aliases array on this
* annotation.)
* Annotation to be applied to methods that create beans in a Spring context. The name of
* the bean is the method name. (It is also possible to specify aliases using the aliases
* array on this annotation.)
*
* <p>Contains information similar to that held in Spring's internal BeanDefinition metadata.</p>
* <p>
* Contains information similar to that held in Spring's internal BeanDefinition metadata.
* </p>
*
* <p>Bean creation methods must be non-private (default, public or protected). Bean creation
* methods may throw any exception, which will be caught and handled by the Spring container on
* processing of the configuration class.<br>
* Bean creation methods must return an object type. The decision to return a class or an interface
* will be significant in the event of proxying. Bean methods that return interfaces will be proxied
* using dynamic proxies; those that return a class will require CGLIB or other subclass-based
* proxying. It is recommended to return an interface where possible, as this is also consistent
* with best practice around loose coupling.</p>
* <p>
* Bean creation methods must be non-private (default, public or protected). Bean creation
* methods may throw any exception, which will be caught and handled by the Spring container
* on processing of the configuration class.<br>
* Bean creation methods must return an object type. The decision to return a class or an
* interface will be significant in the event of proxying. Bean methods that return
* interfaces will be proxied using dynamic proxies; those that return a class will require
* CGLIB or other subclass-based proxying. It is recommended to return an interface where
* possible, as this is also consistent with best practice around loose coupling.
* </p>
*
* <p>Bean creation methods may reference other bean creation methods by calling them directly, as
* follows. This ensures that references between beans are strongly typed:</p>
* <p>
* Bean creation methods may reference other bean creation methods by calling them directly,
* as follows. This ensures that references between beans are strongly typed:
* </p>
*
* @see Configuration
* @see BeanNamingStrategy
@ -66,9 +72,8 @@ import org.springframework.config.java.Validator;
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@Factory(registrarType=BeanRegistrar.class,
callbackType=BeanMethodInterceptor.class,
validatorTypes={BeanValidator.class, IllegalBeanOverrideValidator.class})
@Factory(registrarType = BeanRegistrar.class, callbackType = BeanMethodInterceptor.class, validatorTypes = {
BeanValidator.class, IllegalBeanOverrideValidator.class })
public @interface Bean {
/**
@ -78,18 +83,19 @@ public @interface Bean {
* @see BeanDefinition#ROLE_INFRASTRUCTURE
* @see BeanDefinition#ROLE_SUPPORT
*
* @see AbstractBeanDefinition the 'role' field is assigned by default to ROLE_APPLICATION
* @see AbstractBeanDefinition the 'role' field is assigned by default to
* ROLE_APPLICATION
*/
int role() default BeanDefinition.ROLE_APPLICATION;
/**
* Bean aliases.
*/
String[] aliases() default { };
String[] aliases() default {};
/**
* Scope: whether the bean is a singleton, prototype or custom scope.
* Default is singleton.
* Scope: whether the bean is a singleton, prototype or custom scope. Default is
* singleton.
*/
String scope() default Scopes.SINGLETON;
@ -98,22 +104,23 @@ public @interface Bean {
*/
Autowire autowire() default Autowire.INHERITED;
// /**
// * Bean lazy strategy.
// */
// Lazy lazy() default Lazy.UNSPECIFIED;
//
// /**
// * A bean may be marked as primary, useful for disambiguation when looking
// * up beans by type.
// *
// * @see org.springframework.config.java.context.JavaConfigApplicationContext#getBean(Class);
// */
// Primary primary() default Primary.UNSPECIFIED;
// /**
// * Bean lazy strategy.
// */
// Lazy lazy() default Lazy.UNSPECIFIED;
//
// /**
// * A bean may be marked as primary, useful for disambiguation when looking
// * up beans by type.
// *
// * @see
// org.springframework.config.java.context.JavaConfigApplicationContext#getBean(Class);
// */
// Primary primary() default Primary.UNSPECIFIED;
/**
* Bean init method name. Normally this is not needed, as the initialization
* (with parameterization) can be done directly through java code.
* Bean init method name. Normally this is not needed, as the initialization (with
* parameterization) can be done directly through java code.
*/
String initMethodName() default "";
@ -122,26 +129,25 @@ public @interface Bean {
*/
String destroyMethodName() default "";
// /**
// * Bean dependency check strategy.
// */
// DependencyCheck dependencyCheck() default DependencyCheck.UNSPECIFIED;
// /**
// * Bean dependency check strategy.
// */
// DependencyCheck dependencyCheck() default DependencyCheck.UNSPECIFIED;
/**
* Beans on which the current bean depends on.
*/
String[] dependsOn() default { };
String[] dependsOn() default {};
// /**
// * Metadata for the current bean.
// */
// Meta[] meta() default { };
// /**
// * Metadata for the current bean.
// */
// Meta[] meta() default { };
/**
* Allow the bean to be overridden in another JavaConfig, XML or other
* non-Java configuration. This is consistent with
* DefaultListableBeanFactory's allowBeanDefinitionOverriding property,
* which defaults to true.
* Allow the bean to be overridden in another JavaConfig, XML or other non-Java
* configuration. This is consistent with DefaultListableBeanFactory's
* allowBeanDefinitionOverriding property, which defaults to true.
*
* @return whether overriding of this bean is allowed
*/
@ -165,14 +171,14 @@ class BeanValidator implements Validator {
ModelMethod method = (ModelMethod) object;
// TODO: re-enable for @ScopedProxy support
// if (method.getAnnotation(ScopedProxy.class) == null)
// return;
//
// Bean bean = method.getRequiredAnnotation(Bean.class);
//
// if (bean.scope().equals(DefaultScopes.SINGLETON)
// || bean.scope().equals(DefaultScopes.PROTOTYPE))
// errors.add(new InvalidScopedProxyDeclarationError(method));
// if (method.getAnnotation(ScopedProxy.class) == null)
// return;
//
// Bean bean = method.getRequiredAnnotation(Bean.class);
//
// if (bean.scope().equals(DefaultScopes.SINGLETON)
// || bean.scope().equals(DefaultScopes.PROTOTYPE))
// errors.add(new InvalidScopedProxyDeclarationError(method));
}
}
@ -212,6 +218,3 @@ class IllegalBeanOverrideValidator implements Validator {
}
}

View File

@ -23,6 +23,7 @@ import net.sf.cglib.proxy.MethodProxy;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
/**
* Intercepts the invocation of any {@link Bean}-annotated methods in order to ensure proper
* handling of bean semantics such as scoping and AOP proxying.
@ -35,25 +36,27 @@ import org.springframework.beans.factory.config.ConfigurableBeanFactory;
class BeanMethodInterceptor extends AbstractMethodInterceptor {
/**
* Enhances a {@link Bean @Bean} method to check the supplied BeanFactory for the existence
* of this bean object.
* Enhances a {@link Bean @Bean} method to check the supplied BeanFactory for the
* existence of this bean object.
*/
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
String beanName = getBeanName(method);
// TODO: re-enable for @ScopedProxy support
// boolean isScopedProxy = (AnnotationUtils.findAnnotation(method, ScopedProxy.class) != null);
//
// String scopedBeanName = ScopedProxy.Util.resolveHiddenScopedProxyBeanName(beanName);
// if (isScopedProxy && beanFactory.isCurrentlyInCreation(scopedBeanName))
// beanName = scopedBeanName;
// boolean isScopedProxy = (AnnotationUtils.findAnnotation(method,
// ScopedProxy.class) != null);
//
// String scopedBeanName =
// ScopedProxy.Util.resolveHiddenScopedProxyBeanName(beanName);
// if (isScopedProxy && beanFactory.isCurrentlyInCreation(scopedBeanName))
// beanName = scopedBeanName;
if (factoryContainsBean(beanName)) {
// we have an already existing cached instance of this bean -> retrieve it
Object cachedBean = beanFactory.getBean(beanName);
if (log.isInfoEnabled())
log.info(format("Returning cached singleton object [%s] for @Bean method %s.%s",
cachedBean, method.getDeclaringClass().getSimpleName(), beanName));
log.info(format("Returning cached singleton object [%s] for @Bean method %s.%s", cachedBean,
method.getDeclaringClass().getSimpleName(), beanName));
return cachedBean;
}
@ -62,22 +65,23 @@ class BeanMethodInterceptor extends AbstractMethodInterceptor {
}
/**
* Check the beanFactory to see whether the bean named <var>beanName</var> already exists.
* Accounts for the fact that the requested bean may be "in creation", i.e.: we're in the
* middle of servicing the initial request for this bean. From JavaConfig's perspective,
* this means that the bean does not actually yet exist, and that it is now our job to
* create it for the first time by executing the logic in the corresponding Bean method.
* Check the beanFactory to see whether the bean named <var>beanName</var> already
* exists. Accounts for the fact that the requested bean may be "in creation", i.e.:
* we're in the middle of servicing the initial request for this bean. From JavaConfig's
* perspective, this means that the bean does not actually yet exist, and that it is now
* our job to create it for the first time by executing the logic in the corresponding
* Bean method.
* <p>
* Said another way, this check repurposes {@link ConfigurableBeanFactory#isCurrentlyInCreation(String)}
* to determine whether the container is calling this method or the user is calling this method.
* Said another way, this check repurposes
* {@link ConfigurableBeanFactory#isCurrentlyInCreation(String)} to determine whether
* the container is calling this method or the user is calling this method.
*
* @param beanName name of bean to check for
*
* @return true if <var>beanName</var> already exists in beanFactory
*/
private boolean factoryContainsBean(String beanName) {
return beanFactory.containsBean(beanName)
&& !beanFactory.isCurrentlyInCreation(beanName);
return beanFactory.containsBean(beanName) && !beanFactory.isCurrentlyInCreation(beanName);
}

View File

@ -39,7 +39,7 @@ class BeanRegistrar implements BeanDefinitionRegistrar {
// TODO: SJC-242 method too long
public void register(ModelMethod method, BeanDefinitionRegistry registry) {
RootBeanDefinition beanDef = new JavaConfigBeanDefinition();
RootBeanDefinition beanDef = new ConfigurationClassBeanDefinition();
ConfigurationClass configClass = method.getDeclaringClass();
@ -56,7 +56,8 @@ class BeanRegistrar implements BeanDefinitionRegistrar {
// consider autowiring
if (bean.autowire() != AnnotationUtils.getDefaultValue(Bean.class, "autowire"))
beanDef.setAutowireMode(bean.autowire().value());
else if (defaults.defaultAutowire() != AnnotationUtils.getDefaultValue(Configuration.class, "defaultAutowire"))
else if (defaults.defaultAutowire() != AnnotationUtils.getDefaultValue(Configuration.class,
"defaultAutowire"))
beanDef.setAutowireMode(defaults.defaultAutowire().value());
String beanName = method.getName();
@ -66,7 +67,7 @@ class BeanRegistrar implements BeanDefinitionRegistrar {
BeanDefinition existingBeanDef = getBeanDefinitionIncludingAncestry(beanName, registry);
// is the existing bean definition one that was created by JavaConfig?
if (!(existingBeanDef instanceof JavaConfigBeanDefinition)) {
if (!(existingBeanDef instanceof ConfigurationClassBeanDefinition)) {
// no -> then it's an external override, probably XML
// ensure that overriding is ok
@ -76,9 +77,9 @@ class BeanRegistrar implements BeanDefinitionRegistrar {
}
// overriding is legal, return immediately
logger.info(format("Skipping loading bean definition for %s: a definition for bean '%s' already exists. "
+ "This is likely due to an override in XML.",
method, beanName));
logger.info(format(
"Skipping loading bean definition for %s: a definition for bean '%s' already exists. "
+ "This is likely due to an override in XML.", method, beanName));
return;
}
}
@ -91,14 +92,14 @@ class BeanRegistrar implements BeanDefinitionRegistrar {
registry.registerAlias(beanName, alias);
// TODO: re-enable for Lazy support
// // is this bean marked as primary for disambiguation?
// if (bean.primary() == Primary.TRUE)
// beanDef.setPrimary(true);
//
// // is this bean lazily instantiated?
// if ((bean.lazy() == Lazy.TRUE)
// || ((bean.lazy() == Lazy.UNSPECIFIED) && (defaults.defaultLazy() == Lazy.TRUE)))
// beanDef.setLazyInit(true);
// // is this bean marked as primary for disambiguation?
// if (bean.primary() == Primary.TRUE)
// beanDef.setPrimary(true);
//
// // is this bean lazily instantiated?
// if ((bean.lazy() == Lazy.TRUE)
// || ((bean.lazy() == Lazy.UNSPECIFIED) && (defaults.defaultLazy() == Lazy.TRUE)))
// beanDef.setLazyInit(true);
// does this bean have a custom init-method specified?
String initMethodName = bean.initMethodName();
@ -112,43 +113,49 @@ class BeanRegistrar implements BeanDefinitionRegistrar {
// TODO: re-enable for @ScopedProxy support
// is this method annotated with @ScopedProxy?
// ScopedProxy scopedProxy = method.getAnnotation(ScopedProxy.class);
// if (scopedProxy != null) {
// RootBeanDefinition targetDef = beanDef;
//
// // Create a scoped proxy definition for the original bean name,
// // "hiding" the target bean in an internal target definition.
// String targetBeanName = ScopedProxy.Util.resolveHiddenScopedProxyBeanName(beanName);
// RootBeanDefinition scopedProxyDefinition = new RootBeanDefinition(ScopedProxyFactoryBean.class);
// scopedProxyDefinition.getPropertyValues().addPropertyValue("targetBeanName", targetBeanName);
//
// if (scopedProxy.proxyTargetClass())
// targetDef.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE);
// // ScopedFactoryBean's "proxyTargetClass" default is TRUE, so we
// // don't need to set it explicitly here.
// else
// scopedProxyDefinition.getPropertyValues().addPropertyValue("proxyTargetClass", Boolean.FALSE);
//
// // The target bean should be ignored in favor of the scoped proxy.
// targetDef.setAutowireCandidate(false);
//
// // Register the target bean as separate bean in the factory
// registry.registerBeanDefinition(targetBeanName, targetDef);
//
// // replace the original bean definition with the target one
// beanDef = scopedProxyDefinition;
// }
// ScopedProxy scopedProxy = method.getAnnotation(ScopedProxy.class);
// if (scopedProxy != null) {
// RootBeanDefinition targetDef = beanDef;
//
// // Create a scoped proxy definition for the original bean name,
// // "hiding" the target bean in an internal target definition.
// String targetBeanName =
// ScopedProxy.Util.resolveHiddenScopedProxyBeanName(beanName);
// RootBeanDefinition scopedProxyDefinition = new
// RootBeanDefinition(ScopedProxyFactoryBean.class);
// scopedProxyDefinition.getPropertyValues().addPropertyValue("targetBeanName",
// targetBeanName);
//
// if (scopedProxy.proxyTargetClass())
// targetDef.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE,
// Boolean.TRUE);
// // ScopedFactoryBean's "proxyTargetClass" default is TRUE, so we
// // don't need to set it explicitly here.
// else
// scopedProxyDefinition.getPropertyValues().addPropertyValue("proxyTargetClass",
// Boolean.FALSE);
//
// // The target bean should be ignored in favor of the scoped proxy.
// targetDef.setAutowireCandidate(false);
//
// // Register the target bean as separate bean in the factory
// registry.registerBeanDefinition(targetBeanName, targetDef);
//
// // replace the original bean definition with the target one
// beanDef = scopedProxyDefinition;
// }
// TODO: re-enable for @Meta support
// does this bean method have any @Meta annotations?
// for (Meta meta : bean.meta())
// beanDef.addMetadataAttribute(new BeanMetadataAttribute(meta.key(), meta.value()));
// for (Meta meta : bean.meta())
// beanDef.addMetadataAttribute(new BeanMetadataAttribute(meta.key(),
// meta.value()));
if(bean.dependsOn().length > 0)
if (bean.dependsOn().length > 0)
beanDef.setDependsOn(bean.dependsOn());
logger.info(format("Registering bean definition for @Bean method %s.%s()",
configClass.getName(), beanName));
logger.info(format("Registering bean definition for @Bean method %s.%s()", configClass.getName(),
beanName));
registry.registerBeanDefinition(beanName, beanDef);
@ -165,7 +172,7 @@ class BeanRegistrar implements BeanDefinitionRegistrar {
private BeanDefinition getBeanDefinitionIncludingAncestry(String beanName, BeanDefinitionRegistry registry) {
Assert.isInstanceOf(ConfigurableListableBeanFactory.class, registry);
ConfigurableListableBeanFactory clbf = (ConfigurableListableBeanFactory)registry;
ConfigurableListableBeanFactory clbf = (ConfigurableListableBeanFactory) registry;
do {
if (clbf.containsBeanDefinition(beanName))
@ -177,27 +184,25 @@ class BeanRegistrar implements BeanDefinitionRegistrar {
} else if (parent instanceof ConfigurableListableBeanFactory) {
clbf = (ConfigurableListableBeanFactory) parent;
// TODO: re-enable
// } else if (parent instanceof AbstractApplicationContext) {
// clbf = ((AbstractApplicationContext) parent).getBeanFactory();
// } else if (parent instanceof AbstractApplicationContext) {
// clbf = ((AbstractApplicationContext) parent).getBeanFactory();
} else {
throw new IllegalStateException("unknown parent type: " + parent.getClass().getName());
}
} while (clbf != null);
throw new NoSuchBeanDefinitionException(
format("No bean definition matching name '%s' "
throw new NoSuchBeanDefinitionException(format("No bean definition matching name '%s' "
+ "could be found in %s or its ancestry", beanName, registry));
}
}
/**
* {@link RootBeanDefinition} marker subclass used to signify that a bean definition
* created by JavaConfig as opposed to any other configuration source. Used in bean
* overriding cases where it's necessary to determine whether the bean definition was created
* externally (e.g. via XML).
* {@link RootBeanDefinition} marker subclass used to signify that a bean definition created
* by JavaConfig as opposed to any other configuration source. Used in bean overriding cases
* where it's necessary to determine whether the bean definition was created externally
* (e.g. via XML).
*/
@SuppressWarnings("serial")
// TODO: SJC-242 what to do about JavaConfigBeanDefinition?
class JavaConfigBeanDefinition extends RootBeanDefinition {
class ConfigurationClassBeanDefinition extends RootBeanDefinition {
}

View File

@ -24,13 +24,11 @@ import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
/**
* Transforms a class by adding bytecode for a class-level annotation.
* Checks to ensure that the desired annotation is not already present
* before adding. Used by {@link ConfigurationEnhancer} to dynamically add
* an {@link org.aspectj.lang.Aspect} annotation to an enhanced Configuration
* subclass.
* Transforms a class by adding bytecode for a class-level annotation. Checks to ensure that
* the desired annotation is not already present before adding. Used by
* {@link ConfigurationEnhancer} to dynamically add an {@link org.aspectj.lang.Aspect}
* annotation to an enhanced Configuration subclass.
* <p/>
* This class was originally adapted from examples the ASM 3.0 documentation.
*
@ -44,8 +42,7 @@ class AddAnnotationAdapter extends ClassAdapter {
* Creates a new AddAnnotationAdapter instance.
*
* @param cv the ClassVisitor delegate
* @param annotationDesc name of the annotation to be added
* (in type descriptor format)
* @param annotationDesc name of the annotation to be added (in type descriptor format)
*/
public AddAnnotationAdapter(ClassVisitor cv, String annotationDesc) {
super(cv);
@ -56,7 +53,8 @@ class AddAnnotationAdapter extends ClassAdapter {
* Ensures that the version of the resulting class is Java 5 or better.
*/
@Override
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
public void visit(int version, int access, String name, String signature, String superName,
String[] interfaces) {
int v = (version & 0xFF) < Constants.V1_5 ? Constants.V1_5 : version;
cv.visit(v, access, name, signature, superName, interfaces);
}
@ -85,7 +83,8 @@ class AddAnnotationAdapter extends ClassAdapter {
}
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
public MethodVisitor visitMethod(int access, String name, String desc, String signature,
String[] exceptions) {
addAnnotation();
return cv.visitMethod(access, name, desc, signature, exceptions);
}

View File

@ -46,7 +46,6 @@ import org.springframework.config.java.ConfigurationModel;
import org.springframework.config.java.ModelMethod;
/**
* Enhances {@link Configuration} classes by generating a CGLIB subclass capable of
* interacting with the Spring container to respect bean semantics.
@ -59,25 +58,21 @@ public class ConfigurationEnhancer {
private static final Log log = LogFactory.getLog(ConfigurationEnhancer.class);
private final ArrayList<Class<? extends Callback>> callbackTypes =
new ArrayList<Class<? extends Callback>>();
private final ArrayList<Class<? extends Callback>> callbackTypes = new ArrayList<Class<? extends Callback>>();
private final LinkedHashSet<BeanDefinitionRegistrar> registrars =
new LinkedHashSet<BeanDefinitionRegistrar>();
private final LinkedHashSet<BeanDefinitionRegistrar> registrars = new LinkedHashSet<BeanDefinitionRegistrar>();
private final ArrayList<Callback> callbackInstances =
new ArrayList<Callback>();
private final ArrayList<Callback> callbackInstances = new ArrayList<Callback>();
private final CallbackFilter callbackFilter =
new CallbackFilter() {
private final CallbackFilter callbackFilter = new CallbackFilter() {
public int accept(Method candidateMethod) {
Iterator<BeanDefinitionRegistrar> iter = registrars.iterator();
for(int i=0; iter.hasNext(); i++)
if(iter.next().accepts(candidateMethod))
for (int i = 0; iter.hasNext(); i++)
if (iter.next().accepts(candidateMethod))
return i;
throw new IllegalStateException(format("No registrar is capable of " +
"handling method [%s]. Perhaps you forgot to add a catch-all registrar?",
throw new IllegalStateException(format("No registrar is capable of "
+ "handling method [%s]. Perhaps you forgot to add a catch-all registrar?",
candidateMethod.getName()));
}
};
@ -100,7 +95,8 @@ public class ConfigurationEnhancer {
*
* @see #callbackFilter
*/
private void populateRegistrarsAndCallbacks(DefaultListableBeanFactory beanFactory, ConfigurationModel model) {
private void populateRegistrarsAndCallbacks(DefaultListableBeanFactory beanFactory,
ConfigurationModel model) {
for (ConfigurationClass configClass : model.getAllConfigurationClasses()) {
for (ModelMethod method : configClass.getMethods()) {
@ -108,8 +104,8 @@ public class ConfigurationEnhancer {
Callback callback = method.getCallback();
if(callback instanceof BeanFactoryAware)
((BeanFactoryAware)callback).setBeanFactory(beanFactory);
if (callback instanceof BeanFactoryAware)
((BeanFactoryAware) callback).setBeanFactory(beanFactory);
callbackInstances.add(callback);
}
@ -128,14 +124,14 @@ public class ConfigurationEnhancer {
});
callbackInstances.add(NoOp.INSTANCE);
for(Callback callback : callbackInstances)
for (Callback callback : callbackInstances)
callbackTypes.add(callback.getClass());
}
/**
* Loads the specified class and generates a CGLIB subclass of it equipped with container-aware
* callbacks capable of respecting scoping and other bean semantics.
* Loads the specified class and generates a CGLIB subclass of it equipped with
* container-aware callbacks capable of respecting scoping and other bean semantics.
*
* @return fully-qualified name of the enhanced subclass
*/
@ -150,8 +146,8 @@ public class ConfigurationEnhancer {
subclass = nestOneClassDeeperIfAspect(superclass, subclass);
if (log.isInfoEnabled())
log.info(format("Successfully enhanced %s; enhanced class name is: %s",
configClassName, subclass.getName()));
log.info(format("Successfully enhanced %s; enhanced class name is: %s", configClassName, subclass
.getName()));
return subclass.getName();
}
@ -170,7 +166,7 @@ public class ConfigurationEnhancer {
enhancer.setSuperclass(superclass);
enhancer.setUseFactory(false);
enhancer.setCallbackFilter(callbackFilter);
enhancer.setCallbackTypes(callbackTypes.toArray(new Class<?>[]{}));
enhancer.setCallbackTypes(callbackTypes.toArray(new Class<?>[] {}));
return enhancer;
}
@ -188,22 +184,22 @@ public class ConfigurationEnhancer {
}
/**
* Works around a constraint imposed by the AspectJ 5 annotation-style programming model. See
* comments inline for detail.
* Works around a constraint imposed by the AspectJ 5 annotation-style programming
* model. See comments inline for detail.
*
* @return original subclass instance unless superclass is annnotated with @Aspect, in which
* case a subclass of the subclass is returned
* @return original subclass instance unless superclass is annnotated with @Aspect, in
* which case a subclass of the subclass is returned
*/
private Class<?> nestOneClassDeeperIfAspect(Class<?> superclass, Class<?> origSubclass) {
boolean superclassIsAnAspect = false;
// check for @Aspect by name rather than by class literal to avoid
// requiring AspectJ as a runtime dependency.
for(Annotation anno : superclass.getAnnotations())
if(anno.annotationType().getName().equals("org.aspectj.lang.annotation.Aspect"))
for (Annotation anno : superclass.getAnnotations())
if (anno.annotationType().getName().equals("org.aspectj.lang.annotation.Aspect"))
superclassIsAnAspect = true;
if(!superclassIsAnAspect)
if (!superclassIsAnAspect)
return origSubclass;
// the superclass is annotated with AspectJ's @Aspect.
@ -215,8 +211,8 @@ public class ConfigurationEnhancer {
@Override
protected byte[] transform(byte[] b) throws Exception {
ClassWriter writer = new ClassWriter(false);
ClassAdapter adapter =
new AddAnnotationAdapter(writer, "Lorg/aspectj/lang/annotation/Aspect;");
ClassAdapter adapter = new AddAnnotationAdapter(writer,
"Lorg/aspectj/lang/annotation/Aspect;");
ClassReader reader = new ClassReader(b);
reader.accept(adapter, false);
return writer.toByteArray();

View File

@ -19,12 +19,11 @@ import org.objectweb.asm.AnnotationVisitor;
/**
* An empty AnnotationVisitor that delegates to another AnnotationVisitor.
* This class can be used as a super class to quickly implement
* useful annotation adapter classes, just by overriding the necessary
* methods. Note that for some reason, ASM doesn't provide this class
* (it does provide MethodAdapter and ClassAdapter), thus we're following
* the general pattern and adding our own here.
* An empty AnnotationVisitor that delegates to another AnnotationVisitor. This class can be
* used as a super class to quickly implement useful annotation adapter classes, just by
* overriding the necessary methods. Note that for some reason, ASM doesn't provide this
* class (it does provide MethodAdapter and ClassAdapter), thus we're following the general
* pattern and adding our own here.
*
* @author Chris Beams
*/
@ -33,8 +32,8 @@ class AnnotationAdapter implements AnnotationVisitor {
private AnnotationVisitor delegate;
/**
* Creates a new AnnotationAdapter instance that will delegate
* all its calls to <var>delegate</var>.
* Creates a new AnnotationAdapter instance that will delegate all its calls to
* <var>delegate</var>.
*
* @param delegate In most cases, the delegate will simply be
* {@link AsmUtils#EMPTY_VISITOR}

View File

@ -36,34 +36,37 @@ class AsmUtils {
/**
* @param className a standard, dot-delimeted, fully-qualified Java class name
* @return internal version of className, as per ASM guide section 2.1.2 "Internal Names"
* @return internal version of className, as per ASM guide section 2.1.2
* "Internal Names"
*/
public static String convertClassNameToInternalName(String className) {
return className.replace('.', '/');
}
/**
* Convert a type descriptor to a classname suitable for classloading
* with Class.forName().
* Convert a type descriptor to a classname suitable for classloading with
* Class.forName().
*
* @param typeDescriptor see ASM guide section 2.1.3
*/
public static String convertTypeDescriptorToClassName(String typeDescriptor) {
final String internalName; // See ASM guide section 2.1.2
// TODO: SJC-242 should catch all possible cases. use case statement and switch on char
// TODO: SJC-242 converting from primitive to object here won't be intuitive to users
if("V".equals(typeDescriptor))
// TODO: SJC-242 should catch all possible cases. use case statement and switch on
// char
// TODO: SJC-242 converting from primitive to object here won't be intuitive to
// users
if ("V".equals(typeDescriptor))
return Void.class.getName();
if("I".equals(typeDescriptor))
if ("I".equals(typeDescriptor))
return Integer.class.getName();
if("Z".equals(typeDescriptor))
if ("Z".equals(typeDescriptor))
return Boolean.class.getName();
// strip the leading array/object/primitive identifier
if(typeDescriptor.startsWith("[["))
if (typeDescriptor.startsWith("[["))
internalName = typeDescriptor.substring(3);
else if(typeDescriptor.startsWith("["))
else if (typeDescriptor.startsWith("["))
internalName = typeDescriptor.substring(2);
else
internalName = typeDescriptor.substring(1);
@ -72,8 +75,8 @@ class AsmUtils {
String className = internalName.replace('/', '.');
// and strip trailing semicolon (if present)
if(className.endsWith(";"))
className = className.substring(0, internalName.length()-1);
if (className.endsWith(";"))
className = className.substring(0, internalName.length() - 1);
return className;
}
@ -82,15 +85,16 @@ class AsmUtils {
* @param methodDescriptor see ASM guide section 2.1.4
*/
public static String getReturnTypeFromMethodDescriptor(String methodDescriptor) {
String returnTypeDescriptor = methodDescriptor.substring(methodDescriptor.indexOf(')')+1);
String returnTypeDescriptor = methodDescriptor.substring(methodDescriptor.indexOf(')') + 1);
return convertTypeDescriptorToClassName(returnTypeDescriptor);
}
/**
* Creates a new ASM {@link ClassReader} for <var>pathToClass</var>. Appends '.class'
* to pathToClass before attempting to load.
* Creates a new ASM {@link ClassReader} for <var>pathToClass</var>. Appends '.class' to
* pathToClass before attempting to load.
*
* @throws RuntimeException if <var>pathToClass</var>+.class cannot be found on the classpath
* @throws RuntimeException if <var>pathToClass</var>+.class cannot be found on the
* classpath
* @throws RuntimeException if an IOException occurs when creating the new ClassReader
*/
public static ClassReader newClassReader(String pathToClass) {
@ -99,12 +103,13 @@ class AsmUtils {
}
/**
* Convenience method that simply returns a new ASM {@link ClassReader} instance based on
* the supplied <var>bytes</var> byte array. This method is exactly equivalent to calling
* new ClassReader(byte[]), and is mainly provided for symmetry with usage of
* Convenience method that simply returns a new ASM {@link ClassReader} instance based
* on the supplied <var>bytes</var> byte array. This method is exactly equivalent to
* calling new ClassReader(byte[]), and is mainly provided for symmetry with usage of
* {@link #newClassReader(InputStream)}.
*
* @param bytes byte array that will be provided as input to the new ClassReader instance.
* @param bytes byte array that will be provided as input to the new ClassReader
* instance.
*
* @return
*/
@ -113,10 +118,11 @@ class AsmUtils {
}
/**
* Convenience method that creates and returns a new ASM {@link ClassReader} for the given
* InputStream <var>is</var>, closing the InputStream after creating the ClassReader and rethrowing
* any IOException thrown during ClassReader instantiation as an unchecked exception. Logs and ignores
* any IOException thrown when closing the InputStream.
* Convenience method that creates and returns a new ASM {@link ClassReader} for the
* given InputStream <var>is</var>, closing the InputStream after creating the
* ClassReader and rethrowing any IOException thrown during ClassReader instantiation as
* an unchecked exception. Logs and ignores any IOException thrown when closing the
* InputStream.
*
* @param is InputStream that will be provided to the new ClassReader instance.
*/
@ -124,7 +130,8 @@ class AsmUtils {
try {
return new ClassReader(is);
} catch (IOException ex) {
throw new RuntimeException("An unexpected exception occurred while creating ASM ClassReader: " + ex);
throw new RuntimeException("An unexpected exception occurred while creating ASM ClassReader: "
+ ex);
} finally {
try {
is.close();

View File

@ -34,9 +34,11 @@ import org.springframework.config.java.Factory;
import org.springframework.config.java.ModelClass;
import org.springframework.config.java.ModelMethod;
/**
* Visits a single method declared in a given {@link Configuration} class. Determines whether the
* method is a {@link Factory} method and if so, adds it to the {@link ConfigurationClass}.
* Visits a single method declared in a given {@link Configuration} class. Determines
* whether the method is a {@link Factory} method and if so, adds it to the
* {@link ConfigurationClass}.
*
* @author Chris Beams
*/
@ -70,8 +72,8 @@ class ConfigurationClassMethodVisitor extends MethodAdapter {
}
/**
* Visits a single annotation on this method. Will be called once for each
* annotation present (regardless of its RetentionPolicy).
* Visits a single annotation on this method. Will be called once for each annotation
* present (regardless of its RetentionPolicy).
*/
@Override
public AnnotationVisitor visitAnnotation(String annoTypeDesc, boolean visible) {
@ -79,7 +81,7 @@ class ConfigurationClassMethodVisitor extends MethodAdapter {
Class<? extends Annotation> annoClass = loadToolingSafeClass(annoClassName);
if(annoClass == null)
if (annoClass == null)
return super.visitAnnotation(annoTypeDesc, visible);
Annotation annotation = createMutableAnnotation(annoClass);
@ -90,12 +92,11 @@ class ConfigurationClassMethodVisitor extends MethodAdapter {
}
/**
* Provides the line number of this method within its declaring class. In reality,
* this number is always inaccurate - <var>lineNo</var> represents the line number
* of the first instruction in this method. Method declaration line numbers are
* not in any way tracked in the bytecode. Any tooling or output that reads this
* value will have to compensate and estimate where the actual method declaration
* is.
* Provides the line number of this method within its declaring class. In reality, this
* number is always inaccurate - <var>lineNo</var> represents the line number of the
* first instruction in this method. Method declaration line numbers are not in any way
* tracked in the bytecode. Any tooling or output that reads this value will have to
* compensate and estimate where the actual method declaration is.
*/
@Override
public void visitLineNumber(int lineNo, Label start) {
@ -104,22 +105,22 @@ class ConfigurationClassMethodVisitor extends MethodAdapter {
/**
* Parses through all {@link #annotations} on this method in order to determine whether
* it is a {@link Factory} method or not and if so adds it to the
* enclosing {@link #configClass}.
* it is a {@link Factory} method or not and if so adds it to the enclosing
* {@link #configClass}.
*/
@Override
public void visitEnd() {
for(Annotation anno : annotations) {
if(anno.annotationType().getAnnotation(Factory.class) != null) {
for (Annotation anno : annotations) {
if (anno.annotationType().getAnnotation(Factory.class) != null) {
isModelMethod = true;
break;
}
}
if(!isModelMethod)
if (!isModelMethod)
return;
Annotation[] annoArray = annotations.toArray(new Annotation[] { });
Annotation[] annoArray = annotations.toArray(new Annotation[] {});
ModelMethod method = new ModelMethod(methodName, modifiers, returnType, annoArray);
method.setLineNumber(lineNumber);
configClass.addMethod(method);

View File

@ -37,8 +37,8 @@ import org.springframework.util.ClassUtils;
/**
* Visits a {@link Configuration} class, populating a {@link ConfigurationClass} instance with
* information gleaned along the way.
* Visits a {@link Configuration} class, populating a {@link ConfigurationClass} instance
* with information gleaned along the way.
*
* @author Chris Beams
*/
@ -65,10 +65,8 @@ class ConfigurationClassVisitor extends ClassAdapter {
@Override
public void visitSource(String sourceFile, String debug) {
String resourcePath =
convertClassNameToResourcePath(configClass.getName())
.substring(0, configClass.getName().lastIndexOf('.')+1)
.concat(sourceFile);
String resourcePath = convertClassNameToResourcePath(configClass.getName()).substring(0,
configClass.getName().lastIndexOf('.') + 1).concat(sourceFile);
configClass.setSource(resourcePath);
}
@ -88,7 +86,7 @@ class ConfigurationClassVisitor extends ClassAdapter {
private void visitSuperType(String superTypeDesc) {
// traverse up the type hierarchy unless the next ancestor is java.lang.Object
if(OBJECT_DESC.equals(superTypeDesc))
if (OBJECT_DESC.equals(superTypeDesc))
return;
ConfigurationClassVisitor visitor = new ConfigurationClassVisitor(configClass, model);
@ -119,16 +117,16 @@ class ConfigurationClassVisitor extends ClassAdapter {
}
// TODO: re-enable for @Import support
// if (Import.class.getName().equals(annoTypeName)) {
// ImportStack importStack = ImportStackHolder.getImportStack();
//
// if(importStack.contains(configClass))
// throw new CircularImportException(configClass, importStack);
//
// importStack.push(configClass);
//
// return new ImportAnnotationVisitor(model);
// }
// if (Import.class.getName().equals(annoTypeName)) {
// ImportStack importStack = ImportStackHolder.getImportStack();
//
// if(importStack.contains(configClass))
// throw new CircularImportException(configClass, importStack);
//
// importStack.push(configClass);
//
// return new ImportAnnotationVisitor(model);
// }
// -------------------------------------
// Detect @Plugin annotations
@ -140,12 +138,12 @@ class ConfigurationClassVisitor extends ClassAdapter {
ClassReader reader = AsmUtils.newClassReader(resourcePath);
reader.accept(classVisitor, false);
if(!classVisitor.hasPluginAnnotation())
if (!classVisitor.hasPluginAnnotation())
return super.visitAnnotation(annoTypeDesc, visible);
Class<? extends Annotation> annoType = loadToolingSafeClass(annoTypeName);
if(annoType == null)
if (annoType == null)
return super.visitAnnotation(annoTypeDesc, visible);
Annotation pluginAnno = createMutableAnnotation(annoType);
@ -163,7 +161,7 @@ class ConfigurationClassVisitor extends ClassAdapter {
@Override
public AnnotationVisitor visitAnnotation(String typeDesc, boolean arg1) {
if(Extension.class.getName().equals(AsmUtils.convertTypeDescriptorToClassName(typeDesc))) {
if (Extension.class.getName().equals(AsmUtils.convertTypeDescriptorToClassName(typeDesc))) {
hasPluginAnnotation = true;
return new MutableAnnotationVisitor(pluginAnnotation);
}
@ -184,22 +182,22 @@ class ConfigurationClassVisitor extends ClassAdapter {
* {@link ConfigurationClassMethodVisitor}.
*/
@Override
public MethodVisitor visitMethod(int modifiers, String methodName, String methodDescriptor,
String arg3, String[] arg4) {
public MethodVisitor visitMethod(int modifiers, String methodName, String methodDescriptor, String arg3,
String[] arg4) {
return new ConfigurationClassMethodVisitor(configClass, methodName, methodDescriptor, modifiers);
}
/**
* Implementation deals with inner classes here even though it would have
* been more intuitive to deal with outer classes. Due to limitations in ASM
* (resulting from limitations in the VM spec) we cannot directly look for outer classes
* in all cases, so instead build up a model of {@link #innerClasses} and process
* declaring class logic in a kind of inverted manner.
* Implementation deals with inner classes here even though it would have been more
* intuitive to deal with outer classes. Due to limitations in ASM (resulting from
* limitations in the VM spec) we cannot directly look for outer classes in all cases,
* so instead build up a model of {@link #innerClasses} and process declaring class
* logic in a kind of inverted manner.
*/
@Override
public void visitInnerClass(String name, String outerName, String innerName, int access) {
if(processInnerClasses == false)
if (processInnerClasses == false)
return;
String innerClassName = convertResourcePathToClassName(name);
@ -208,8 +206,8 @@ class ConfigurationClassVisitor extends ClassAdapter {
// if the innerClassName is equal to configClassName, we just
// ran into the outermost inner class look up the outer class
// associated with this
if(innerClassName.equals(configClassName)) {
if(innerClasses.containsKey(outerName)) {
if (innerClassName.equals(configClassName)) {
if (innerClasses.containsKey(outerName)) {
configClass.setDeclaringClass(innerClasses.get(outerName));
}
return;
@ -217,18 +215,18 @@ class ConfigurationClassVisitor extends ClassAdapter {
ConfigurationClass innerConfigClass = new ConfigurationClass();
ConfigurationClassVisitor ccVisitor =
new ConfigurationClassVisitor(innerConfigClass, new ConfigurationModel());
ConfigurationClassVisitor ccVisitor = new ConfigurationClassVisitor(innerConfigClass,
new ConfigurationModel());
ccVisitor.setProcessInnerClasses(false);
ClassReader reader = AsmUtils.newClassReader(name);
reader.accept(ccVisitor, false);
if(innerClasses.containsKey(outerName))
if (innerClasses.containsKey(outerName))
innerConfigClass.setDeclaringClass(innerClasses.get(outerName));
// is the inner class a @Configuration class? If so, add it to the list
if(innerConfigClass.getMetadata() != null)
if (innerConfigClass.getMetadata() != null)
innerClasses.put(name, innerConfigClass);
}
}

View File

@ -16,16 +16,15 @@
package org.springframework.config.java.internal.parsing;
/**
* Note: the visibility of this interface would be reduced to package-private
* save for an obscure restriction of JDK dynamic proxies.
* {@link MutableAnnotationUtils#createMutableAnnotation(Class)} creates a proxy
* based on two interfaces: this one, and whatever annotation is currently being
* parsed. The restriction is that both interfaces may not be package-private if
* they are in separate packages. In order to avoid unnecessarily restricting
* the visibility options for user-defined annotations, this interface becomes
* public. Because it is in the internal.* package, it won't pollute the public
* API, but developers should take caution not to use this annotation outside
* the internal.parsing package.
* Note: the visibility of this interface would be reduced to package-private save for an
* obscure restriction of JDK dynamic proxies.
* {@link MutableAnnotationUtils#createMutableAnnotation(Class)} creates a proxy based on
* two interfaces: this one, and whatever annotation is currently being parsed. The
* restriction is that both interfaces may not be package-private if they are in separate
* packages. In order to avoid unnecessarily restricting the visibility options for
* user-defined annotations, this interface becomes public. Because it is in the internal.*
* package, it won't pollute the public API, but developers should take caution not to use
* this annotation outside the internal.parsing package.
*
* @author Chris Beams
*/

View File

@ -53,7 +53,7 @@ class MutableAnnotationArrayVisitor extends AnnotationAdapter {
String annoTypeName = AsmUtils.convertTypeDescriptorToClassName(annoTypeDesc);
Class<? extends Annotation> annoType = loadToolingSafeClass(annoTypeName);
if(annoType == null)
if (annoType == null)
return super.visitAnnotation(na, annoTypeDesc);
Annotation anno = createMutableAnnotation(annoType);
@ -64,7 +64,7 @@ class MutableAnnotationArrayVisitor extends AnnotationAdapter {
@Override
public void visitEnd() {
Class<?> arrayType = mutableAnno.getAttributeType(attribName);
Object[] array = (Object[])Array.newInstance(arrayType.getComponentType(), 0);
Object[] array = (Object[]) Array.newInstance(arrayType.getComponentType(), 0);
mutableAnno.setAttributeValue(attribName, values.toArray(array));
}

View File

@ -41,7 +41,7 @@ final class MutableAnnotationInvocationHandler implements InvocationHandler {
// pre-populate the attributes hash will all the names
// and default values of the attributes defined in 'annoType'
Method[] attribs = annoType.getDeclaredMethods();
for(Method attrib : attribs) {
for (Method attrib : attribs) {
this.attributes.put(attrib.getName(), getDefaultValue(annoType, attrib.getName()));
this.attributeTypes.put(attrib.getName(), getAttributeType(annoType, attrib.getName()));
}
@ -55,33 +55,33 @@ final class MutableAnnotationInvocationHandler implements InvocationHandler {
String methodName = method.getName();
// first -> check to see if this method is an attribute on our annotation
if(attributes.containsKey(methodName))
if (attributes.containsKey(methodName))
return attributes.get(methodName);
// second -> is it a method from java.lang.annotation.Annotation?
if(methodName.equals("annotationType"))
if (methodName.equals("annotationType"))
return annoType;
// third -> is it a method from java.lang.Object?
if(methodName.equals("toString"))
if (methodName.equals("toString"))
return format("@%s(%s)", annoType.getName(), getAttribs());
if(methodName.equals("equals"))
if (methodName.equals("equals"))
return isEqualTo(proxy, args[0]);
if(methodName.equals("hashCode"))
if (methodName.equals("hashCode"))
return calculateHashCode(proxy);
// finally -> is it a method specified by MutableAnno?
if(methodName.equals("setAttributeValue")) {
attributes.put((String)args[0], args[1]);
if (methodName.equals("setAttributeValue")) {
attributes.put((String) args[0], args[1]);
return null; // setAttributeValue has a 'void' return type
}
if(methodName.equals("getAttributeType"))
if (methodName.equals("getAttributeType"))
return attributeTypes.get(args[0]);
throw new UnsupportedOperationException("this proxy does not support method: " + methodName);
@ -102,8 +102,10 @@ final class MutableAnnotationInvocationHandler implements InvocationHandler {
final int attribValueHashCode;
if (attribValue == null)
// memberValue may be null when a mutable annotation is being added to a collection
// and before it has actually been visited (and populated) by MutableAnnotationVisitor
// memberValue may be null when a mutable annotation is being added to a
// collection
// and before it has actually been visited (and populated) by
// MutableAnnotationVisitor
attribValueHashCode = 0;
else if (attribValue.getClass().isArray())
attribValueHashCode = Arrays.hashCode((Object[]) attribValue);
@ -117,15 +119,17 @@ final class MutableAnnotationInvocationHandler implements InvocationHandler {
}
/**
* Compares <var>proxy</var> object and <var>other</var> object by comparing the return values
* of the methods specified by their common {@link Annotation} ancestry.
* Compares <var>proxy</var> object and <var>other</var> object by comparing the return
* values of the methods specified by their common {@link Annotation} ancestry.
* <p/>
* <var>other</var> must be the same type as or a subtype of <var>proxy</var>.
* Will return false otherwise.
* <var>other</var> must be the same type as or a subtype of <var>proxy</var>. Will
* return false otherwise.
* <p/>
* Eagerly returns true if {@code proxy} == <var>other</var></p>
* Eagerly returns true if {@code proxy} == <var>other</var>
* </p>
* <p/>
* Conforms strictly to the equals() specification for Annotation</p>
* Conforms strictly to the equals() specification for Annotation
* </p>
*
* @see Annotation#equals(Object)
*/
@ -136,7 +140,7 @@ final class MutableAnnotationInvocationHandler implements InvocationHandler {
if (other == null)
return false;
if(!annoType.isAssignableFrom(other.getClass()))
if (!annoType.isAssignableFrom(other.getClass()))
return false;
for (String attribName : attributes.keySet()) {
@ -191,8 +195,7 @@ final class MutableAnnotationInvocationHandler implements InvocationHandler {
try {
method = annotationType.getDeclaredMethod(attributeName);
}
catch (Exception ex) {
} catch (Exception ex) {
ReflectionUtils.handleReflectionException(ex);
}

View File

@ -23,9 +23,9 @@ import java.lang.reflect.Proxy;
class MutableAnnotationUtils {
/**
* Creates a {@link MutableAnnotation} for {@code annoType}.
* JDK dynamic proxies are used, and the returned proxy implements
* both {@link MutableAnnotation} and annotation type {@code A}
* Creates a {@link MutableAnnotation} for {@code annoType}. JDK dynamic proxies are
* used, and the returned proxy implements both {@link MutableAnnotation} and annotation
* type {@code A}
*
* @param <A> annotation type that must be supplied and returned
* @param annoType type of annotation to create
@ -33,7 +33,7 @@ class MutableAnnotationUtils {
public static <A extends Annotation> A createMutableAnnotation(Class<A> annoType) {
MutableAnnotationInvocationHandler handler = new MutableAnnotationInvocationHandler(annoType);
ClassLoader classLoader = MutableAnnotationUtils.class.getClassLoader();
Class<?>[] interfaces = new Class<?>[] {annoType, MutableAnnotation.class};
Class<?>[] interfaces = new Class<?>[] { annoType, MutableAnnotation.class };
@SuppressWarnings("unchecked")
A mutableAnno = (A) Proxy.newProxyInstance(classLoader, interfaces, handler);

View File

@ -38,9 +38,9 @@ class MutableAnnotationVisitor implements AnnotationVisitor {
protected final MutableAnnotation mutableAnno;
/**
* Creates a new {@link MutableAnnotationVisitor} instance that will populate
* the the attributes of the given <var>mutableAnno</var>. Accepts {@link Annotation}
* instead of {@link MutableAnnotation} to avoid the need for callers to typecast.
* Creates a new {@link MutableAnnotationVisitor} instance that will populate the the
* attributes of the given <var>mutableAnno</var>. Accepts {@link Annotation} instead of
* {@link MutableAnnotation} to avoid the need for callers to typecast.
*
* @param mutableAnno {@link MutableAnnotation} instance to visit and populate
*
@ -51,7 +51,7 @@ class MutableAnnotationVisitor implements AnnotationVisitor {
*/
public MutableAnnotationVisitor(Annotation mutableAnno) {
Assert.isInstanceOf(MutableAnnotation.class, mutableAnno, "annotation must be mutable");
this.mutableAnno = (MutableAnnotation)mutableAnno;
this.mutableAnno = (MutableAnnotation) mutableAnno;
}
public AnnotationVisitor visitArray(final String attribName) {
@ -67,7 +67,7 @@ class MutableAnnotationVisitor implements AnnotationVisitor {
Class<?> classVal = loadToolingSafeClass(fqClassName);
if(classVal == null)
if (classVal == null)
return;
mutableAnno.setAttributeValue(attribName, classVal);
@ -84,7 +84,7 @@ class MutableAnnotationVisitor implements AnnotationVisitor {
Class<? extends Enum> enumClass = loadToolingSafeClass(enumClassName);
if(enumClass == null)
if (enumClass == null)
return;
Enum enumValue = Enum.valueOf(enumClass, strEnumValue);
@ -95,7 +95,7 @@ class MutableAnnotationVisitor implements AnnotationVisitor {
String annoTypeName = AsmUtils.convertTypeDescriptorToClassName(attribAnnoTypeDesc);
Class<? extends Annotation> annoType = loadToolingSafeClass(annoTypeName);
if(annoType == null)
if (annoType == null)
return AsmUtils.EMPTY_VISITOR.visitAnnotation(attribName, attribAnnoTypeDesc);
Annotation anno = createMutableAnnotation(annoType);
@ -110,6 +110,7 @@ class MutableAnnotationVisitor implements AnnotationVisitor {
return new MutableAnnotationVisitor(anno);
}
public void visitEnd() { }
public void visitEnd() {
}
}

View File

@ -38,9 +38,9 @@ public @interface Extension {
Class<? extends ExtensionAnnotationBeanDefinitionRegistrar<?>> handler();
/**
* The order in which this plugin will be processed
* relative to others. Per the semantics of {@link Ordered},
* lower integer values will be treated as higher priority.
* The order in which this plugin will be processed relative to others. Per the
* semantics of {@link Ordered}, lower integer values will be treated as higher
* priority.
*
* @see Ordered
*/

View File

@ -15,7 +15,6 @@
*/
package org.springframework.config.java.support;
import static java.lang.String.*;
import static org.springframework.config.java.Util.*;
@ -44,10 +43,9 @@ import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
/**
* Reads a given fully-populated {@link ConfigurationModel}, registering bean definitions with
* the given {@link BeanDefinitionRegistry} based on its contents.
* Reads a given fully-populated {@link ConfigurationModel}, registering bean definitions
* with the given {@link BeanDefinitionRegistry} based on its contents.
* <p>
* This class was modeled after the {@link BeanDefinitionReader} hierarchy, but does not
* implement/extend any of its artifacts as {@link ConfigurationModel} is not a
@ -70,8 +68,8 @@ class ConfigurationModelBeanDefinitionReader {
}
/**
* Reads {@code model}, registering bean definitions with {@link #beanFactory}
* based on its contents.
* Reads {@code model}, registering bean definitions with {@link #beanFactory} based on
* its contents.
*
* @return number of bean definitions generated
*/
@ -85,8 +83,8 @@ class ConfigurationModelBeanDefinitionReader {
}
/**
* Reads a particular {@link ConfigurationClass}, registering bean definitions
* for the class itself, all its {@link Factory} methods and all its {@link Extension}
* Reads a particular {@link ConfigurationClass}, registering bean definitions for the
* class itself, all its {@link Factory} methods and all its {@link Extension}
* annotations.
*/
private void loadBeanDefinitionsForConfigurationClass(ConfigurationClass configClass) {
@ -112,7 +110,8 @@ class ConfigurationModelBeanDefinitionReader {
Class<?> beanClass = RequiredAnnotationBeanPostProcessor.class;
String beanName = beanClass.getName() + "#0";
requiredAnnotationPostProcessor.setBeanClass(beanClass);
requiredAnnotationPostProcessor.setResourceDescription("ensures @Required methods have been invoked");
requiredAnnotationPostProcessor
.setResourceDescription("ensures @Required methods have been invoked");
beanFactory.registerBeanDefinition(beanName, requiredAnnotationPostProcessor);
}
@ -125,9 +124,11 @@ class ConfigurationModelBeanDefinitionReader {
// and potentially has PropertyValues and ConstructorArgs)
if (beanFactory.containsBeanDefinition(configBeanName)) {
if (log.isInfoEnabled())
log.info(format("Copying property and constructor arg values from existing bean definition for "
log.info(format(
"Copying property and constructor arg values from existing bean definition for "
+ "@Configuration class %s to new bean definition", configBeanName));
AbstractBeanDefinition existing = (AbstractBeanDefinition)beanFactory.getBeanDefinition(configBeanName);
AbstractBeanDefinition existing = (AbstractBeanDefinition) beanFactory
.getBeanDefinition(configBeanName);
configBeanDef.setPropertyValues(existing.getPropertyValues());
configBeanDef.setConstructorArgumentValues(existing.getConstructorArgumentValues());
configBeanDef.setResource(existing.getResource());
@ -141,8 +142,8 @@ class ConfigurationModelBeanDefinitionReader {
/**
* Reads a particular {@link ModelMethod}, registering bean definitions
* with {@link #beanFactory} based on its contents.
* Reads a particular {@link ModelMethod}, registering bean definitions with
* {@link #beanFactory} based on its contents.
*
* @see Factory
*/
@ -152,15 +153,14 @@ class ConfigurationModelBeanDefinitionReader {
@SuppressWarnings("unchecked")
private void loadBeanDefinitionsForExtensionAnnotation(Annotation anno) {
//ExtensionAnnotationUtils.getRegistrarFor(anno).registerBeanDefinitionsWith(beanFactory);
// ExtensionAnnotationUtils.getRegistrarFor(anno).registerBeanDefinitionsWith(beanFactory);
// there is a fixed assumption that in order for this annotation to have
// been registered in the first place, it must be meta-annotated with @Plugin
// assert this as an invariant now
Class<?> annoClass = anno.getClass();
Extension extensionAnno = AnnotationUtils.findAnnotation(annoClass, Extension.class);
Assert.isTrue(extensionAnno != null,
format("%s annotation is not annotated as a @%s",
annoClass, Extension.class.getSimpleName()));
Assert.isTrue(extensionAnno != null, format("%s annotation is not annotated as a @%s", annoClass,
Extension.class.getSimpleName()));
Class<? extends ExtensionAnnotationBeanDefinitionRegistrar> extHandlerClass = extensionAnno.handler();
@ -177,9 +177,9 @@ class ConfigurationModelBeanDefinitionReader {
private Integer getOrder(Annotation a) {
Extension plugin = a.annotationType().getAnnotation(Extension.class);
if(plugin == null)
throw new IllegalArgumentException(
"annotation was not annotated with @Plugin: " + a.annotationType());
if (plugin == null)
throw new IllegalArgumentException("annotation was not annotated with @Plugin: "
+ a.annotationType());
return plugin.order();
}
}

View File

@ -40,8 +40,8 @@ import org.springframework.util.ClassUtils;
/**
* {@link BeanFactoryPostProcessor} used for bootstrapping {@link Configuration @Configuration}
* beans from Spring XML files.
* {@link BeanFactoryPostProcessor} used for bootstrapping {@link Configuration
* @Configuration} beans from Spring XML files.
*/
public class ConfigurationPostProcessor implements Ordered, BeanFactoryPostProcessor {
@ -49,8 +49,8 @@ public class ConfigurationPostProcessor implements Ordered, BeanFactoryPostProce
/**
* Returns the order in which this {@link BeanPostProcessor} will be executed.
* Returns {@link Ordered#HIGHEST_PRECEDENCE}.
* Returns the order in which this {@link BeanPostProcessor} will be executed. Returns
* {@link Ordered#HIGHEST_PRECEDENCE}.
*/
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
@ -58,12 +58,12 @@ public class ConfigurationPostProcessor implements Ordered, BeanFactoryPostProce
/**
* Searches <var>beanFactory</var> for any {@link Configuration} classes in order
* to parse and enhance them. Also registers any {@link BeanPostProcessor} objects
* Searches <var>beanFactory</var> for any {@link Configuration} classes in order to
* parse and enhance them. Also registers any {@link BeanPostProcessor} objects
* necessary to fulfill JavaConfig requirements.
*/
public void postProcessBeanFactory(ConfigurableListableBeanFactory clBeanFactory) throws BeansException {
if(!(clBeanFactory instanceof DefaultListableBeanFactory))
if (!(clBeanFactory instanceof DefaultListableBeanFactory))
throw new IllegalStateException("beanFactory must be of type "
+ DefaultListableBeanFactory.class.getSimpleName());
@ -78,7 +78,8 @@ public class ConfigurationPostProcessor implements Ordered, BeanFactoryPostProce
private void parseAnyConfigurationClasses(DefaultListableBeanFactory beanFactory, ConfigurationModel model) {
// linked map is important for maintaining predictable ordering of configuration classes.
// linked map is important for maintaining predictable ordering of configuration
// classes.
// this is important in bean / value override situations.
LinkedHashMap<String, ClassPathResource> configClassResources = new LinkedHashMap<String, ClassPathResource>();
@ -93,7 +94,8 @@ public class ConfigurationPostProcessor implements Ordered, BeanFactoryPostProce
}
}
ConfigurationModelBeanDefinitionReader modelBeanDefinitionReader = new ConfigurationModelBeanDefinitionReader(beanFactory);
ConfigurationModelBeanDefinitionReader modelBeanDefinitionReader = new ConfigurationModelBeanDefinitionReader(
beanFactory);
ConfigurationParser parser = new ConfigurationParser(model);
for (String id : configClassResources.keySet())
@ -102,21 +104,22 @@ public class ConfigurationPostProcessor implements Ordered, BeanFactoryPostProce
ArrayList<UsageError> errors = new ArrayList<UsageError>();
model.validate(errors);
if (errors.size() > 0)
throw new MalformedConfigurationException(errors.toArray(new UsageError[] { }));
throw new MalformedConfigurationException(errors.toArray(new UsageError[] {}));
modelBeanDefinitionReader.loadBeanDefinitions(model);
}
/**
* Post-processes a BeanFactory in search of Configuration class BeanDefinitions; any candidates
* are then enhanced by a {@link ConfigurationEnhancer}. Candidate status is determined by
* BeanDefinition attribute metadata.
* Post-processes a BeanFactory in search of Configuration class BeanDefinitions; any
* candidates are then enhanced by a {@link ConfigurationEnhancer}. Candidate status is
* determined by BeanDefinition attribute metadata.
*
* @author Chris Beams
* @see ConfigurationEnhancer
* @see BeanFactoryPostProcessor
*/
private void enhanceAnyConfigurationClasses(DefaultListableBeanFactory beanFactory, ConfigurationModel model) {
private void enhanceAnyConfigurationClasses(DefaultListableBeanFactory beanFactory,
ConfigurationModel model) {
ConfigurationEnhancer enhancer = new ConfigurationEnhancer(beanFactory, model);
@ -133,7 +136,10 @@ public class ConfigurationPostProcessor implements Ordered, BeanFactoryPostProce
String enhancedClassName = enhancer.enhance(configClassName);
if (logger.isDebugEnabled())
logger.debug(String.format("Replacing bean definition '%s' existing class name '%s' with enhanced class name '%s'",
logger
.debug(String
.format(
"Replacing bean definition '%s' existing class name '%s' with enhanced class name '%s'",
beanName, configClassName, enhancedClassName));
beanDef.setBeanClassName(enhancedClassName);
@ -146,22 +152,21 @@ public class ConfigurationPostProcessor implements Ordered, BeanFactoryPostProce
}
/**
* Determines whether the class for <var>beanDef</var> is a {@link Configuration}-annotated
* class. Returns false if <var>beanDef</var> has no class specified.
* Determines whether the class for <var>beanDef</var> is a {@link Configuration}
* -annotated class. Returns false if <var>beanDef</var> has no class specified.
* <p>
* Note: the classloading used within should not be problematic or interfere with tooling in any
* way. BeanFactoryPostProcessing happens only during actual runtime processing via
* {@link JavaConfigApplicationContext} or via XML using {@link ConfigurationPostProcessor}. In
* any case, tooling (Spring IDE) will hook in at a lower level than this class and
* thus never encounter this classloading. Should this become problematic, it would not be
* too difficult to replace the following with ASM logic that traverses the class hierarchy in
* order to find whether the class is directly or indirectly annotated with
* {@link Configuration}.
* Note: the classloading used within should not be problematic or interfere with
* tooling in any way. BeanFactoryPostProcessing happens only during actual runtime
* processing via {@link JavaConfigApplicationContext} or via XML using
* {@link ConfigurationPostProcessor}. In any case, tooling (Spring IDE) will hook in at
* a lower level than this class and thus never encounter this classloading. Should this
* become problematic, it would not be too difficult to replace the following with ASM
* logic that traverses the class hierarchy in order to find whether the class is
* directly or indirectly annotated with {@link Configuration}.
*/
private static boolean isConfigClass(BeanDefinition beanDef) {
String className = beanDef.getBeanClassName();
return className != null
&& loadRequiredClass(className).isAnnotationPresent(Configuration.class);
return className != null && loadRequiredClass(className).isAnnotationPresent(Configuration.class);
}
}

View File

@ -2,6 +2,7 @@ package test.basic;
import org.junit.Before;
public abstract class AbstractJavaConfigTests {
@Before
@ -9,6 +10,6 @@ public abstract class AbstractJavaConfigTests {
}
//protected
// protected
}

View File

@ -13,11 +13,12 @@ import org.springframework.context.support.ClassPathXmlApplicationContext;
import test.beans.Colour;
import test.beans.TestBean;
public class AutowiredConfigurationTests {
public @Test void test() {
public @Test
void test() {
ClassPathXmlApplicationContext factory = new ClassPathXmlApplicationContext(
AutowiredConfigurationTests.class.getSimpleName() + ".xml",
AutowiredConfigurationTests.class);
AutowiredConfigurationTests.class.getSimpleName() + ".xml", AutowiredConfigurationTests.class);
assertThat(factory.getBean("colour", Colour.class), equalTo(Colour.RED));
assertThat(factory.getBean("testBean", TestBean.class).getName(), equalTo(Colour.RED.toString()));
@ -25,21 +26,26 @@ public class AutowiredConfigurationTests {
@Configuration
static class AutowiredConfig {
private @Autowired Colour colour;
private @Autowired
Colour colour;
public @Bean TestBean testBean() {
public @Bean
TestBean testBean() {
return new TestBean(colour.toString());
}
}
@Configuration
static class ColorConfig {
public @Bean Colour colour() { return Colour.RED; }
public @Bean
Colour colour() {
return Colour.RED;
}
}
public @Test void testValueInjection() {
public @Test
void testValueInjection() {
System.setProperty("myProp", "foo");
ClassPathXmlApplicationContext factory = new ClassPathXmlApplicationContext(
@ -55,7 +61,8 @@ public class AutowiredConfigurationTests {
@Value("#{systemProperties.myProp}")
private String name = "default";
public @Bean TestBean testBean() {
public @Bean
TestBean testBean() {
return new TestBean(name);
}
}

View File

@ -17,25 +17,28 @@ import org.springframework.config.java.support.ConfigurationPostProcessor;
import test.beans.ITestBean;
import test.beans.TestBean;
public class BasicTests {
/**
* Creates a new {@link BeanFactory}, populates it with a {@link BeanDefinition} for
* each of the given {@link Configuration} <var>configClasses</var>, and then post-processes
* the factory using JavaConfig's {@link ConfigurationPostProcessor}. When complete,
* the factory is ready to service requests for any {@link Bean} methods declared by
* <var>configClasses</var>.
* each of the given {@link Configuration} <var>configClasses</var>, and then
* post-processes the factory using JavaConfig's {@link ConfigurationPostProcessor}.
* When complete, the factory is ready to service requests for any {@link Bean} methods
* declared by <var>configClasses</var>.
*
* @param configClasses the {@link Configuration} classes under test. may be an empty list.
* @param configClasses the {@link Configuration} classes under test. may be an empty
* list.
*
* @return fully initialized and post-processed {@link BeanFactory}
*/
private static BeanFactory initBeanFactory(Class<?>... configClasses) {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
for(Class<?> configClass : configClasses) {
for (Class<?> configClass : configClasses) {
String configBeanName = configClass.getName();
factory.registerBeanDefinition(configBeanName, rootBeanDefinition(configClass).getBeanDefinition());
factory.registerBeanDefinition(configBeanName, rootBeanDefinition(configClass)
.getBeanDefinition());
}
new ConfigurationPostProcessor().postProcessBeanFactory(factory);
@ -57,7 +60,8 @@ public class BasicTests {
@Configuration
static class SimplestPossibleConfig {
public @Bean String stringBean() {
public @Bean
String stringBean() {
return "foo";
}
}
@ -77,22 +81,23 @@ public class BasicTests {
@Configuration
static class ConfigWithPrototypeBean {
public @Bean TestBean foo() {
public @Bean
TestBean foo() {
TestBean foo = new TestBean("foo");
foo.setSpouse(bar());
return foo;
}
public @Bean TestBean bar() {
public @Bean
TestBean bar() {
TestBean bar = new TestBean("bar");
bar.setSpouse(baz());
return bar;
}
@Bean(scope=Scopes.PROTOTYPE)
@Bean(scope = Scopes.PROTOTYPE)
public TestBean baz() {
return new TestBean("bar");
}
}
}

View File

@ -34,5 +34,7 @@ public class Colour extends ShortCodedLabeledEnum {
public static final Colour PURPLE = new Colour(3, "PURPLE");
private Colour(int code, String label) { super(code, label); }
private Colour(int code, String label) {
super(code, label);
}
}

View File

@ -22,10 +22,16 @@ public class DependsOnTestBean {
private int state;
public void setTestBean(TestBean tb) { this.tb = tb; }
public void setTestBean(TestBean tb) {
this.tb = tb;
}
public int getState() { return state; }
public int getState() {
return state;
}
public TestBean getTestBean() { return tb; }
public TestBean getTestBean() {
return tb;
}
}

View File

@ -19,8 +19,8 @@ import java.io.IOException;
/**
* Interface used for test beans. Two methods are the same as on Person, but if
* this extends person it breaks quite a few tests
* Interface used for test beans. Two methods are the same as on Person, but if this extends
* person it breaks quite a few tests
*
* @author Rod Johnson
*/

View File

@ -48,7 +48,9 @@ public class IndexedTestBean {
private SortedMap<String, TestBean> sortedMap;
public IndexedTestBean() { this(true); }
public IndexedTestBean() {
this(true);
}
public IndexedTestBean(boolean populate) {
if (populate) {
@ -84,32 +86,60 @@ public class IndexedTestBean {
this.map.put("key4", list);
}
public TestBean[] getArray() { return array; }
public TestBean[] getArray() {
return array;
}
public void setArray(TestBean[] array) { this.array = array; }
public void setArray(TestBean[] array) {
this.array = array;
}
public Collection<?> getCollection() { return collection; }
public Collection<?> getCollection() {
return collection;
}
public void setCollection(Collection<TestBean> collection) { this.collection = collection; }
public void setCollection(Collection<TestBean> collection) {
this.collection = collection;
}
public List<TestBean> getList() { return list; }
public List<TestBean> getList() {
return list;
}
public void setList(List<TestBean> list) { this.list = list; }
public void setList(List<TestBean> list) {
this.list = list;
}
public Set<TestBean> getSet() { return set; }
public Set<TestBean> getSet() {
return set;
}
public void setSet(Set<TestBean> set) { this.set = set; }
public void setSet(Set<TestBean> set) {
this.set = set;
}
public SortedSet<TestBean> getSortedSet() { return sortedSet; }
public SortedSet<TestBean> getSortedSet() {
return sortedSet;
}
public void setSortedSet(SortedSet<TestBean> sortedSet) { this.sortedSet = sortedSet; }
public void setSortedSet(SortedSet<TestBean> sortedSet) {
this.sortedSet = sortedSet;
}
public Map<String, Object> getMap() { return map; }
public Map<String, Object> getMap() {
return map;
}
public void setMap(Map<String, Object> map) { this.map = map; }
public void setMap(Map<String, Object> map) {
this.map = map;
}
public SortedMap<String, TestBean> getSortedMap() { return sortedMap; }
public SortedMap<String, TestBean> getSortedMap() {
return sortedMap;
}
public void setSortedMap(SortedMap<String, TestBean> sortedMap) { this.sortedMap = sortedMap; }
public void setSortedMap(SortedMap<String, TestBean> sortedMap) {
this.sortedMap = sortedMap;
}
}

View File

@ -25,7 +25,8 @@ public class NestedTestBean implements INestedTestBean {
private String company = "";
public NestedTestBean() { }
public NestedTestBean() {
}
public NestedTestBean(String company) {
setCompany(company);

View File

@ -99,11 +99,16 @@ public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOt
private List<?> pets;
public TestBean() { }
public TestBean() {
}
public TestBean(String name) { this.name = name; }
public TestBean(String name) {
this.name = name;
}
public TestBean(ITestBean spouse) { this.spouse = spouse; }
public TestBean(ITestBean spouse) {
this.spouse = spouse;
}
public TestBean(String name, int age) {
this.name = name;
@ -115,39 +120,73 @@ public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOt
this.someProperties = someProperties;
}
public void setBeanName(String beanName) { this.beanName = beanName; }
public void setBeanName(String beanName) {
this.beanName = beanName;
}
public String getBeanName() { return beanName; }
public String getBeanName() {
return beanName;
}
public void setBeanFactory(BeanFactory beanFactory) { this.beanFactory = beanFactory; }
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
public BeanFactory getBeanFactory() { return beanFactory; }
public BeanFactory getBeanFactory() {
return beanFactory;
}
public void setPostProcessed(boolean postProcessed) { this.postProcessed = postProcessed; }
public void setPostProcessed(boolean postProcessed) {
this.postProcessed = postProcessed;
}
public boolean isPostProcessed() { return postProcessed; }
public boolean isPostProcessed() {
return postProcessed;
}
public String getName() { return name; }
public String getName() {
return name;
}
public void setName(String name) { this.name = name; }
public void setName(String name) {
this.name = name;
}
public String getSex() { return sex; }
public String getSex() {
return sex;
}
public void setSex(String sex) { this.sex = sex; }
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() { return age; }
public int getAge() {
return age;
}
public void setAge(int age) { this.age = age; }
public void setAge(int age) {
this.age = age;
}
public boolean isJedi() { return jedi; }
public boolean isJedi() {
return jedi;
}
public void setJedi(boolean jedi) { this.jedi = jedi; }
public void setJedi(boolean jedi) {
this.jedi = jedi;
}
public ITestBean getSpouse() { return spouse; }
public ITestBean getSpouse() {
return spouse;
}
public void setSpouse(ITestBean spouse) { this.spouse = spouse; }
public void setSpouse(ITestBean spouse) {
this.spouse = spouse;
}
public String getTouchy() { return touchy; }
public String getTouchy() {
return touchy;
}
public void setTouchy(String touchy) throws Exception {
if (touchy.indexOf('.') != -1) {
@ -161,77 +200,149 @@ public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOt
this.touchy = touchy;
}
public String getCountry() { return country; }
public String getCountry() {
return country;
}
public void setCountry(String country) { this.country = country; }
public void setCountry(String country) {
this.country = country;
}
public String[] getStringArray() { return stringArray; }
public String[] getStringArray() {
return stringArray;
}
public void setStringArray(String[] stringArray) { this.stringArray = stringArray; }
public void setStringArray(String[] stringArray) {
this.stringArray = stringArray;
}
public Integer[] getSomeIntegerArray() { return someIntegerArray; }
public Integer[] getSomeIntegerArray() {
return someIntegerArray;
}
public void setSomeIntegerArray(Integer[] someIntegerArray) { this.someIntegerArray = someIntegerArray; }
public void setSomeIntegerArray(Integer[] someIntegerArray) {
this.someIntegerArray = someIntegerArray;
}
public Date getDate() { return date; }
public Date getDate() {
return date;
}
public void setDate(Date date) { this.date = date; }
public void setDate(Date date) {
this.date = date;
}
public Float getMyFloat() { return myFloat; }
public Float getMyFloat() {
return myFloat;
}
public void setMyFloat(Float myFloat) { this.myFloat = myFloat; }
public void setMyFloat(Float myFloat) {
this.myFloat = myFloat;
}
public Collection<?> getFriends() { return friends; }
public Collection<?> getFriends() {
return friends;
}
public void setFriends(Collection<?> friends) { this.friends = friends; }
public void setFriends(Collection<?> friends) {
this.friends = friends;
}
public Set<?> getSomeSet() { return someSet; }
public Set<?> getSomeSet() {
return someSet;
}
public void setSomeSet(Set<?> someSet) { this.someSet = someSet; }
public void setSomeSet(Set<?> someSet) {
this.someSet = someSet;
}
public Map<?, ?> getSomeMap() { return someMap; }
public Map<?, ?> getSomeMap() {
return someMap;
}
public void setSomeMap(Map<?, ?> someMap) { this.someMap = someMap; }
public void setSomeMap(Map<?, ?> someMap) {
this.someMap = someMap;
}
public List<?> getSomeList() { return someList; }
public List<?> getSomeList() {
return someList;
}
public void setSomeList(List<?> someList) { this.someList = someList; }
public void setSomeList(List<?> someList) {
this.someList = someList;
}
public Properties getSomeProperties() { return someProperties; }
public Properties getSomeProperties() {
return someProperties;
}
public void setSomeProperties(Properties someProperties) { this.someProperties = someProperties; }
public void setSomeProperties(Properties someProperties) {
this.someProperties = someProperties;
}
public INestedTestBean getDoctor() { return doctor; }
public INestedTestBean getDoctor() {
return doctor;
}
public INestedTestBean getLawyer() { return lawyer; }
public INestedTestBean getLawyer() {
return lawyer;
}
public void setDoctor(INestedTestBean bean) { doctor = bean; }
public void setDoctor(INestedTestBean bean) {
doctor = bean;
}
public void setLawyer(INestedTestBean bean) { lawyer = bean; }
public void setLawyer(INestedTestBean bean) {
lawyer = bean;
}
public Number getSomeNumber() { return someNumber; }
public Number getSomeNumber() {
return someNumber;
}
public void setSomeNumber(Number someNumber) { this.someNumber = someNumber; }
public void setSomeNumber(Number someNumber) {
this.someNumber = someNumber;
}
public Colour getFavouriteColour() { return favouriteColour; }
public Colour getFavouriteColour() {
return favouriteColour;
}
public void setFavouriteColour(Colour favouriteColour) { this.favouriteColour = favouriteColour; }
public void setFavouriteColour(Colour favouriteColour) {
this.favouriteColour = favouriteColour;
}
public Boolean getSomeBoolean() { return someBoolean; }
public Boolean getSomeBoolean() {
return someBoolean;
}
public void setSomeBoolean(Boolean someBoolean) { this.someBoolean = someBoolean; }
public void setSomeBoolean(Boolean someBoolean) {
this.someBoolean = someBoolean;
}
public IndexedTestBean getNestedIndexedBean() { return nestedIndexedBean; }
public IndexedTestBean getNestedIndexedBean() {
return nestedIndexedBean;
}
public void setNestedIndexedBean(IndexedTestBean nestedIndexedBean) { this.nestedIndexedBean = nestedIndexedBean; }
public void setNestedIndexedBean(IndexedTestBean nestedIndexedBean) {
this.nestedIndexedBean = nestedIndexedBean;
}
public List<?> getOtherColours() { return otherColours; }
public List<?> getOtherColours() {
return otherColours;
}
public void setOtherColours(List<?> otherColours) { this.otherColours = otherColours; }
public void setOtherColours(List<?> otherColours) {
this.otherColours = otherColours;
}
public List<?> getPets() { return pets; }
public List<?> getPets() {
return pets;
}
public void setPets(List<?> pets) { this.pets = pets; }
public void setPets(List<?> pets) {
this.pets = pets;
}
/**
* @see ITestBean#exceptional(Throwable)
@ -242,23 +353,34 @@ public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOt
}
}
public void unreliableFileOperation() throws IOException { throw new IOException(); }
public void unreliableFileOperation() throws IOException {
throw new IOException();
}
/**
* @see ITestBean#returnsThis()
*/
public Object returnsThis() { return this; }
public Object returnsThis() {
return this;
}
/**
* @see IOther#absquatulate()
*/
public void absquatulate() { }
public void absquatulate() {
}
public int haveBirthday() { return age++; }
public int haveBirthday() {
return age++;
}
public void destroy() { this.destroyed = true; }
public void destroy() {
this.destroyed = true;
}
public boolean wasDestroyed() { return destroyed; }
public boolean wasDestroyed() {
return destroyed;
}
@Override
public boolean equals(Object other) {
@ -275,7 +397,9 @@ public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOt
}
@Override
public int hashCode() { return this.age; }
public int hashCode() {
return this.age;
}
public int compareTo(Object other) {
if ((this.name != null) && (other instanceof TestBean)) {