bean tag attributes introduction and study notes the role of Spring Source

The traditional Spring project, xml configuration bean is often encountered in the code, then the bean configuration time, the role of these attributes, what is it? 
Although the project now boot the rise, a lot less xml-based configuration, but if you can understand the role of these tags for our annotation-based configuration is also a great benefit

first part of the test involves attaching code for the class:
@Data
public class Student {

    private int age;

    private  String name = "test" ;

    private int sex;
}

  

1 . The above mentioned id : Unique name of the Bean. It must be a legal XMLID, unique in the entire XML document.

 

 

 

2. name : to create one or more aliases for the id. It can be any letter symbol. Comma, semicolon, or space between a plurality of aliases.

 

 

 Wherein the portion of the processing bean tag resolution source code is as follows:

 

    public  BeanDefinitionHolder parseBeanDefinitionElement (Element ele, @Nullable BeanDefinition containingBean) {
String id
= ele.getAttribute (ID_ATTRIBUTE); NameAttr String = ele.getAttribute (NAME_ATTRIBUTE);
// parse nanme property,
// where MULTI_VALUE_ATTRIBUTE_DELIMITERS String = Final static public ",;";
// we can find the name attribute delimiters that supports three of
List
<String> aliases = new new the ArrayList <> (); IF (StringUtils.hasLength (nameAttr)) {
// use the delimiter is divided into an array, as the bean alias String[] nameArr
= StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS); aliases.addAll(Arrays.asList(nameArr)); } BeanName String = id;
// if the id attribute is empty, say the first alias as the name of the bean
IF (!! StringUtils.hasText (beanName) && aliases.isEmpty ()) { beanName = aliases.remove(0); if (logger.isTraceEnabled()) { logger.trace("No XML 'id' specified - using '" + beanName + "' as bean name and " + aliases + " as aliases"); } } if (containingBean == null) { checkNameUniqueness(beanName, aliases, ele); } AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean); if (beanDefinition != null) { if (!StringUtils.hasText(beanName)) { try { if (containingBean != null) { beanName = BeanDefinitionReaderUtils.generateBeanName ( beanDefinition, this.readerContext.getRegistry(), true); } else { beanName = this.readerContext.generateBeanName(beanDefinition); // Register an alias for the plain bean class name, if still possible, // if the generator returned the class name plus a suffix. // This is expected for Spring 1.2/2.0 backwards compatibility. String beanClassName = beanDefinition.getBeanClassName(); if (beanClassName != null && beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() && !this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) { aliases.add(beanClassName); } } if (logger.isTraceEnabled()) { logger.trace("Neither XML 'id' nor 'name' specified - " + "using generated bean name [" + beanName + "]"); } } catch (Exception ex) { error(ex.getMessage(), ele); return null; } } String[] aliasesArray = StringUtils.toStringArray(aliases); return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray); } return null; }


3. class : class is used to define the fully qualified name (the package name + class name). We used to specify the fully qualified name of class to be instantiated

4. parent: Bean subclass definition that references its parent Bean. Bean subclass inherits all the properties of the parent class Bean, Bean subclasses can also override properties of the parent class of Bean.
At this time, the parent class by initializing sub-property attribute only some similar properties


5. abstract (default is "false"): used to define whether the abstract Bean Bean. It indicates that the Bean will not be instantiated, generally used for the parent class Bean, Bean primarily because the parent class is a subclass Bean for use inherit.

<the bean ID = "parent" class = "com.cbl.spring.model.Parent" abstract = "to true"> 
<Property name = "username" value = "parent name" />
<-! <Property name = " parent "value =" parent "/> ->
</ the bean>
// this abstract is provided to true, this parentbean not be instantiated, the code will be given
Parent parent = applicationContext.getBean(Parent.class);

Source code analysis section properties:
public AbstractBeanDefinition parseBeanDefinitionAttributes (Element ele, String beanName,
            @Nullable BeanDefinition containingBean, AbstractBeanDefinition bd) {
          
// The new version of the singleton property no longer play any role, in the old version 1.x have to use, the new version uses the scope attribute
IF (ele.hasAttribute (SINGLETON_ATTRIBUTE)) { error("Old 1.x 'singleton' attribute in use - upgrade to 'scope' declaration", ele); } else if (ele.hasAttribute(SCOPE_ATTRIBUTE)) { bd.setScope(ele.getAttribute(SCOPE_ATTRIBUTE)); } else if (containingBean != null) { // Take default from containing bean in case of an inner bean definition. bd.setScope(containingBean.getScope()); } if (ele.hasAttribute(ABSTRACT_ATTRIBUTE)) { bd.setAbstract(TRUE_VALUE.equals(ele.getAttribute(ABSTRACT_ATTRIBUTE))); } String lazyInit = ele.getAttribute(LAZY_INIT_ATTRIBUTE); if (DEFAULT_VALUE.equals(lazyInit)) { lazyInit = this.defaults.getLazyInit(); } bd.setLazyInit(TRUE_VALUE.equals(lazyInit)); String autowire = ele.getAttribute(AUTOWIRE_ATTRIBUTE); bd.setAutowireMode(getAutowireMode(autowire)); if (ele.hasAttribute(DEPENDS_ON_ATTRIBUTE)) { String dependsOn = ele.getAttribute(DEPENDS_ON_ATTRIBUTE); bd.setDependsOn(StringUtils.tokenizeToStringArray(dependsOn, MULTI_VALUE_ATTRIBUTE_DELIMITERS)); } String autowireCandidate = ele.getAttribute(AUTOWIRE_CANDIDATE_ATTRIBUTE); if ("".equals(autowireCandidate) || DEFAULT_VALUE.equals(autowireCandidate)) { String candidatePattern = this.defaults.getAutowireCandidates(); if (candidatePattern != null) { String[] patterns = StringUtils.commaDelimitedListToStringArray(candidatePattern); bd.setAutowireCandidate(PatternMatchUtils.simpleMatch(patterns, beanName)); } } else { bd.setAutowireCandidate(TRUE_VALUE.equals(autowireCandidate)); } if (ele.hasAttribute(PRIMARY_ATTRIBUTE)) { bd.setPrimary(TRUE_VALUE.equals(ele.getAttribute(PRIMARY_ATTRIBUTE))); } if (ele.hasAttribute(INIT_METHOD_ATTRIBUTE)) { String initMethodName = ele.getAttribute(INIT_METHOD_ATTRIBUTE); bd.setınitmethodn clearance (initmethodn up); } else if (this.defaults.getInitMethod() != null) { bd.setInitMethodName(this.defaults.getInitMethod()); bd.setEnforceInitMethod(false); } if (ele.hasAttribute(DESTROY_METHOD_ATTRIBUTE)) { String destroyMethodName = ele.getAttribute(DESTROY_METHOD_ATTRIBUTE); bd.setDestroyMethodName(destroyMethodName); } else if (this.defaults.getDestroyMethod() != null) { bd.setDestroyMethodName(this.defaults.getDestroyMethod()); bd.setEnforceDestroyMethod(false); } if (ele.hasAttribute(FACTORY_METHOD_ATTRIBUTE)) { bd.setFactoryMethodName(ele.getAttribute(FACTORY_METHOD_ATTRIBUTE)); } if (ele.hasAttribute(FACTORY_BEAN_ATTRIBUTE)) { bd.setFactoryBeanName(ele.getAttribute(FACTORY_BEAN_ATTRIBUTE)); } return bd; } // beanDifinition some of the attributes defined by default
public abstract class AbstractBeanDefinition extends BeanMetadataAttributeAccessor
        implements BeanDefinition, Cloneable {

    /**
     * Constant for the default scope name: {@code ""}, equivalent to singleton
     * status unless overridden from a parent bean definition (if applicable).
     * /

// Default is null, equivalent to the singleton, unless the parent class to the cover, that is to say when the default value Singleton public static Final String SCOPE_DEFAULT = "" ; /** * Constant that indicates no autowiring at all. * @see #setAutowireMode */ public static final int AUTOWIRE_NO = AutowireCapableBeanFactory.AUTOWIRE_NO; /** * Constant that indicates autowiring bean properties by name. * @see #setAutowireMode */ public static final int AUTOWIRE_BY_NAME = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME; /** * Constant that indicates autowiring bean properties by type. * @see #setAutowireMode */ public static final int AUTOWIRE_BY_TYPE = AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE; /** * Constant that indicates autowiring a constructor. * @see #setAutowireMode */ public static final int AUTOWIRE_CONSTRUCTOR = AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR; /** * Constant that indicates determining an appropriate autowire strategy * through introspection of the bean class. * @see #setAutowireMode * @deprecated as of Spring 3.0: If you are using mixed autowiring strategies, * use annotation-based autowiring for clearer demarcation of autowiring needs. */ @Deprecated public static final int AUTOWIRE_AUTODETECT = AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT; /** * Constant that indicates no dependency check at all. * @see #setDependencyCheck */ public static final int DEPENDENCY_CHECK_NONE = 0; /** * Constant that indicates dependency checking for object references. * @see #setDependencyCheck */ public static final int DEPENDENCY_CHECK_OBJECTS = 1; /** * Constant that indicates dependency checking for "simple" properties. * @see #setDependencyCheck * @see org.springframework.beans.BeanUtils#isSimpleProperty */ public static final int DEPENDENCY_CHECK_SIMPLE = 2; /** * Constant that indicates dependency checking for all properties * (object references as well as "simple" properties). * @see #setDependencyCheck */ public static final int DEPENDENCY_CHECK_ALL = 3; /** * Constant that indicates the container should attempt to infer the * {@link #setDestroyMethodName destroy method name} for a bean as opposed to * explicit specification of a method name. The value {@value} is specifically * designed to include characters otherwise illegal in a method name, ensuring * no possibility of collisions with legitimately named methods having the same * name. * <p>Currently, the method names detected during destroy method inference * are "close" and "shutdown", if present on the specific bean class. */ public static final String INFER_METHOD = "(inferred)"; @Nullable private volatile Object beanClass; @Nullable private String scope = SCOPE_DEFAULT; Private Boolean abstractFlag = to false ;
// the default values lazy loaded to false
Private Boolean lazyInit = to false ; private int autowireMode = AUTOWIRE_NO; private int dependencyCheck = DEPENDENCY_CHECK_NONE; @Nullable private String[] dependsOn; private boolean autowireCandidate = true; private boolean primary = false; private final Map<String, AutowireCandidateQualifier> qualifiers = new LinkedHashMap<>(); @Nullable private Supplier<?> instanceSupplier; private boolean nonPublicAccessAllowed = true; private boolean lenientConstructorResolution = true; @Nullable private String factoryBeanName; @Nullable private String factoryMethodName; @Nullable private ConstructorArgumentValues constructorArgumentValues; @Nullable private MutablePropertyValues propertyValues; @Nullable private MethodOverrides methodOverrides; @Nullable private String initMethodName; @Nullable private String destroyMethodName; private boolean enforceInitMethod = true; private boolean enforceDestroyMethod = true; private boolean synthetic = false; }

 




6. singleton (default is "true"): Bean is defined whether the Singleton (singleton).
The new version of the singleton property no longer play any role, in the old version 1.x have to use, the new version uses the scope attribute

7.lazy-init (default is "false"): used to define the Bean whether to implement lazy initialization. If it is "false", it will initialize all SingletonBean when BeanFactory start. Conversely if it is "true", it only began to create SingletonBean only when Bean request.

Beandefinition objects created by default is GenericBeanDefinition, and GenericBeanDefinition inherited from AbstractBeanDefinition, then the two classes the default values provided in our default on some of its properties necessarily use, property values can be seen from some members of the above variables, the default value It is false

8, autowire (automatic assembly, the default is "default"): It defines Bean automatic loading mode.

8.1, "no": No autowiring function.

8.2, "byName": automatically assembled by the Bean property name.

8.3, "byType": automatically assembled by the type of Bean.

8.4, "constructor": similar byType, but it is used for automated assembly of constructor arguments.

8.5, "autodetect": Decide whether to use "constructor" or use "byType" mechanism through introspection (introspection) Bean class.

9, dependency-check (dependency checking, the default is "default"): It is used to ensure that the components so dependencies Bean described by JavaBean are satisfied. When used with automated assembly feature, it is especially useful.

9.1, none: no dependency checking.

9.2, objects: only between object dependency checks.

9.3, simple: only primitive types and String type dependent check

9.4, all: check all types of dependency. It includes the foregoing objects and simple.

10, depends-on (dependent objects): The Bean dependent upon initialization object that will be created before the Bean initialization.

11, init-method: initialization method used to define the Bean, it will be called after Bean assembly. It must be a non-parametric method.

12, destroy-method: Bean used to define methods of destruction, which is called when the BeanFactory closed. Similarly, it must be a non-parametric method. It can only be applied singletonBean.

13, factory-method: create the Bean object factory method definition. It is used in the following "factory-bean", it indicates that the Bean is created by the factory method. At this point, "class" attribute failure.

14, factory-bean: define the creation of the Bean object factory class. If the "factory-bean" the "class" attribute failure.

15, autowire-candidate: xml format configuration when using the bean, the property autowire-candidate <bean /> element is set to false, so that the container when looking for automatic assembling objects, which will not be considered the bean, i.e., it will not be considered as other candidate bean automatic assembly, but the bean itself or may be used to inject other automated assembly bean.

Guess you like

Origin www.cnblogs.com/cheng21553516/p/12026652.html