Spring's core module

Source: Internet
Author: User


The main function of the core module is to implement control inversion and dependency injection, bean configuration, and load. The core module has beans, beanfactory, beandefinitions, ApplicationContext and other concepts

Beanfactory

Beanfactory is a container for instantiating, configuring, and managing many beans

In a Web program, when the user does not need to instantiate the Beanfactory,web program to load, it automatically instantiates the beanfactory and loads the desired beans, setting the individual beans to the servlet, In the action of struts or hibernate resources

In a Java desktop program, you need to get the bean from beanfactory, so you need to instantiate the beanfactory, for example, to load a configuration file under Classpath:

Classpathresource  res = new Classpathresource ("Applicationcontext.xml"); Xmlbeanfactory  factory = new Xmlbeanfactory  (res) IService service= factory.getbean ("service"); Factory.destroysingletons ();

Or use a file stream to load a configuration file from anywhere

InputStream in  = new FileInputStream ("C:\\applicationcontext.xml"); Xmlbeanfactory  factory = new Xmlbeanfactory  (in);

Or load multiple configuration files (passed in as strings) with Classpathxmlapplicationcontext

Classpathxmlapplicationcontext  appContext = new Classpathxmlapplicationcontext (new String [] {" Applicationcontext.xml "," Applicationcontext-part2.xml "}); Beanfactoryfactory = (beanfactory) Appcontext;//applicationcontext inherits from Beanfactory interface

Configuration Bean

Factory mode

If a bean cannot be instantiated directly from new, but is created by a method in the factory class, the class attribute of <bean> needs to be configured as a factory class (or the Factory-bean property is configured as a factory class object)

<bean  id= "Exambean" class = "examples. Mybeanfactory "method=" CreateInstance "/><!--equivalent to the following configuration--><bean  id=" examBean2 "Factory-bean =" Examples. Mybeanfactory "method=" CreateInstance "/>

constructor function

If the bean's constructor has parameters, you need to specify the parameters of the constructor

<bean id = "Exambean" class= "examples. Examplebean ">      <constructor-args><ref bean=" Anotherbeanid "/></constructor-args>      <constructor-args><ref bean= "AnotherBeanId2"/></constructor-args>      <constructor-args ><value>1</value></constructor-args></bean>

Parameters are ordered in the same order as the constructor parameters

Single-state mode

The bean can be defined as a single-state mode, and in non-single-state mode, a new object is generated each time the bean is requested.

General configuration such as data sources is a single-state mode

<bean id= "Examplebean" class= "examples. Examlebean "singleton=" false "/>

Property Properties

The Destroy-method property configures the shutdown method and, if configured, calls the method when the Java object is discarded, and some data sources, sessionfactory objects need to be configured with a Destroy-method shutdown method

<property name= "Examproperty" value= "PValue"/>

Equivalent to

<property name= "Examproperty" >      <value>pValue</value></property>

Attention:

<property name= "Password" >      <value></value></property>

The password is set to "" Instead of NULL if you want to set NULL to be

<property name= "Password" >      <null/></property>

<ref> Properties

Spring configuration files can be referenced to each other, using the <ref> tag with the Bean ID attribute when referencing

You can also use the internal configuration

<bean id= "DAO" class = "Com.clf.DaoImpl" ></bean><bean id= "Serviceimpl" class= "COM.CLF". Serviceimpl ">      <property name=" DAO ">             <ref bean=" dao "/>      </property></bean>

Equivalent to internal configuration

<property name= "DAO" >      <bean class= "Com.clf.DaoImpl"/></property>

In addition to using the bean properties of <ref>, you can also use local, parent, which is the same as the bean properties, but local can only use bean,parent in this profile to use only the beans in the parent configuration file

<list> Properties

<property name= "propname" >      <list>             <value>string, Integer, double and other types of data </value>             <ref bean= "DataSource"/>      </list></property>

<set> Properties

<property name= "propname" >      <set>             <value>string, Integer, double and other types of data </value>             <ref bean= "DataSource"/>      </set></property>

<map> Properties

<property name= "propname" >      <map>             <entry key= "Key1" >                    <value>string, Integer, Double type data </value>             </entry>             <entry key-ref= "Key2" >                    <ref bean= "DataSource"/>             </entry>      </map></property>

<props> Properties

<property name= "propname" >      <props>             <prop key= "url" >http://localhost:8080/clf</prop >             <prop key= "name" >clf</prop>      </props ></property>

<destroy-method> and <init-method> Properties

<bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource" destroy-method= "Close" >......</bean >


Spring calls the Close method when it logs off these resources

Some objects need to execute some initialization code after instantiation, but the code cannot be written into the constructor, this time the initialization code can be written into a method, and use <init-method> to specify the method

<bean id= "C" class= "Com.clf.SpringExample"  init-method= "init" >

Depends-on Property

Spring will instantiate the bean sequentially according to the Bean in the configuration file, but it is sometimes necessary to instantiate the B object before instantiating the A object, which can be forced to instantiate the B object first by using the Depends-on property.

<bean id= "A" clas= "COM.CLF.A" depends-on= "B" ></bean><bean id= "B" clas= "com.clf.b" ></bean>

The difference between <idref> and <ref>

<idref> is the same as <ref>, it's all about configuring Java objects, except that,<idref> has only beans and local properties, and no Parent property

When spring loads an XML configuration file, the bean that checks for <idref> configuration is not in, and <ref> is only checked on the first call, in other words, if the bean does not exist,<idref> throws an error when the program is started , <ref> will only throw errors in the run

<autowire>

Automatic assembly rules can be set through the bean's Autowire property. After using Autowire, you do not need to use <propertyname= "" value= ""/> Explicitly set the Bean's properties, dependencies, spring will automatically find the properties that match the condition based on reflection, set to the bean

The Autowire property defines not the name of the property that needs to be automatically assembled, but the rules for automatic assembly, and once configured, all properties follow the rules defined by the Autowire

No: Automatic assembly is not enabled. Autowire the default value.

ByName: Finds and injects JavaBean-dependent objects by the name of the property. For example, if the class computer has a property printer, specifying that its Autowire property is ByName, the Spring IOC container looks for a bean with Id/name property printer in the configuration file and injects it using the setter method.

Bytype: Finds and injects JavaBean-dependent objects through the type of the property. For example, if the class computer has an attribute printer and the type is printer, the Spring IOC container will look for the bean with the class attribute bytype and inject it with the setter method, after specifying that its Autowire property is printer.

Constructor: Like Bytype, a dependent object is also found by type. The difference with Bytype is that it is not injected using setter methods, but instead uses constructor injection.

AutoDetect: Automatic selection of injection modes between Bytype and constructor.

Default: Determined by the Default-autowire property of the parent tag <beans>.

Dependency-check

Sometimes, some beans have an error in the configuration of their properties, which will not have any exception when the program starts, and will remain dormant until spring calls the bean.

The dependency check checks to see if the property is set, and if a dependency check is configured, the program starts with a configuration check to detect the error in a timely manner.

However, it should be noted that the dependency check is very blunt, for example, set to object, will check all Java object Properties, as long as a property is not set, will throw an exception

No or default: Do not make any checks, default

Simple: Check only basic types, collection properties

object: Check only Java object properties

All: Check All properties

Bean's advanced Features

beannameaware interface Help Bean knows its ID in the config file

Import  Org.springframework.beans.factory.beannameaware;public class  Beannametest Implementsbeannameaware {      private String beanname;      Spring calls the method public      void Setbeanname (String beanname) {             this.beanname = beanname;      }     }

The beanfactoryaware interface helps the bean know which Beanfactory has instantiated itself

public interface  beanfactoryaware{      void Setbeanfactoryaware (Beanfactory beanfactory) throws Beanexception ;}

Usage with Beannameaware

In addition, there are some common methods

Boolean Containsbean (String) determines whether a bean with the specified name exists

Object Getbean (String) returns the specified name if no exception is thrown by the bean

Object Getbean (String,class) returns the bean with the specified name and translates to the specified class object

Boolean Issingleton (String) to determine whether the bean with the specified name is configured as a single-state mode

string []getaliases (String) returns the alias of the bean with the specified name

The Initializingbean interface invokes the initialization method after the bean is instantiated and all properties are set. However, using this interface is coupled with the spring code and is therefore deprecated, and Spring recommends using the Init-method configuration

Public interface initializingbean{public      void Afterpropertiesset ();  Call this method when initializing}

The Disposablebean interface calls the Destroy method when the bean object is discarded

Public interface disposablebean{public      void Destroy ();  Call this method when destroying}

Property Overlay

For some parameters, a more practical and simpler approach is to use the properties configuration instead of configuring it in spring's configuration file

propertyplaceholderconfigurer allows certain parameters of the XML configuration to be configured in the properties file

<bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource" destroy-method= "Close" >      < Property Name= "Driverclassname" value= "${jdbc.driverclassname}"/>      <property name= "url" value= "${jdbc.url } "/>      <property name=" username "value=" ${jdbc. Username} "/>      <property name=" password "value=" ${ Jdbc. Password} "/></bean> <bean id=" Propertyconfigurer "class=" Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer ">      <property name=" Loaction " Value= "Classpath:jdbc.properties" ></bean>

Jdbc.properties

Jdbc.driverclassname= Com.mysql.jdbc.Driverjdbc.url =jdbc:mysql://localhost:3306/clf?characterencoding= Utf-8jdbc.username =clfjdbc.password =admin


Spring's core module

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.