Spring control inversion and dependency Injection

Source: Internet
Author: User

 

 

The environment used: dom4j spring 2.5.6, with: Spring. Jar dom4j. Jar common-logging.jar

Unit tests were performed on applications using Junit-4. And adopts interface-oriented programming (Abstract The interface layer)

 

Spring configuration file: Beans. xml

 

<? XML version = "1.0" encoding = "UTF-8"?>
<Beans xmlns = "http://www.springframework.org/schema/beans"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xsi: schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<! -- Instantiate the bean to implement control inversion, that is, the spirng container is responsible for creating objects -->
<Bean id = "personservice" class = "com. SGL. Imp. personservicebean"> </bean>

<! -- Perform dependency injection using the set method -->

<Bean id = "daoPerson" class = "com. sgl. dao. imp. PersonDaoBean"> </bean>
<Bean id = "personService4" class = "com. sgl. imp. PersonServiceBean">
<Property name = "personDao" ref = "daoPerson"> </property>
</Bean>

</Beans>

 

The source java files used are as follows:

1. Custom Application context (CORE)

Package sgl. spring. principle;

Import java. beans. Introspector;
Import java. beans. PropertyDescriptor;
Import java. lang. reflect. Method;
Import java.net. URL;
Import java. util. ArrayList;
Import java. util. HashMap;
Import java. util. List;
Import java. util. Map;
Import java. util. Logging. level;
Import java. util. Logging. Logger;
Import org. dom4j. Document;
Import org. dom4j. element;
Import org. dom4j. XPath;
Import org. dom4j. Io. saxreader;

/**
*
* @ Author Administrator
*/
Public class sglclasspathxmlapplicationcontext {

Private list <beandefinition> beandefines = new arraylist <beandefinition> (); // stores all bean instances
Private Map <string, Object> sinletons = new hashmap <string, Object> (); // stores the ing between bean and its associated class instances.

Public sglclasspathxmlapplicationcontext (string filename ){
This. readxml (filename );
This. instanceBeans ();
This. injectObject ();
}

/**
* Read the xml configuration file
* @ Param fileName configuration file name
*/
Private void readXml (String fileName ){
SAXReader saxReader = new SAXReader ();
Document document = null;

URL xmlPath = this. getClass (). getClassLoader (). getResource (fileName );
Try {
Document = saxReader. read (xmlPath );
Map <String, String> nsMap = new HashMap <String, String> ();
NsMap. put ("ns", "http://www.springframework.org/schema/beans"); // Add namespace
XPath xsub = document. createXPath ("// ns: beans/ns: bean"); // create/beans/bean query path
Xsub. setNamespaceURIs (nsMap); // you can specify a namespace.
List <Element> beans = xsub. selectNodes (document); // obtain all beans in the document

For (Element element: beans ){
String id = element. attributevalue ("ID"); // obtain the bean ID attribute
String classname = element. attributevalue ("class"); // obtain the class attribute of bean
XPath propertypath = element. createxpath ("ns: Property"); // create a bean/property query path
Propertypath. setnamespaceuris (nsmap); // set the namespace to be consistent with the root element.
List <element> propertys = propertypath. selectnodes (element); // obtain all properties under element (bean)

Beandefinition beandefine = new beandefinition (ID, classname); // instantiate a bean
// Set the property. because there may be multiple properties, use a loop
For (element property: propertys ){
String name = property. attributevalue ("name"); // obtain the name attribute of the property.
String ref = property. attributevalue ("Ref"); // obtain the ref attribute of the property.
System. out. println ("" + name + "" + ref );
PropertyDefinition propertyDefine = new PropertyDefinition (name, ref );
BeanDefine. getPropertys (). add (propertyDefine );
}
BeanDefines. add (beanDefine); // add the bean instance to the array
}

} Catch (Exception ex ){
Logger. getLogger (SglClassPathXmlApplicationContext. class. getName (). log (Level. SEVERE, null, ex );
}
}

/**
* Bean instantiation
*/
Private void instanceBeans (){
System. out. println ("Start of Instantiation ");
For (BeanDefinition beanDefine: beanDefines ){
If (beanDefine. getClassName ()! = Null &&! "". Equals (beanDefine. getClassName (). trim ())){
Try {
// Use java reflection technology to obtain java class instances
System. out. println ("beanID" + beanDefine. getId ());
Sinletons. put (beanDefine. getId (), Class. forName (beanDefine. getClassName (). newInstance ());
} Catch (Exception ex ){
Logger. getLogger (SglClassPathXmlApplicationContext. class. getName (). log (Level. SEVERE, null, ex );
}
}
}
System. out. println ("End of Instantiation ");
}

/**
* Retrieve bean instances
* @ Param beanName
* @ Return
*/
Public Object getBean (String beanName ){
Return this. sinletons. get (beanName );
}

Private void injectObject (){
For (beandefinition beandefine: beandefines) {// traverses all <beans>, because all <beans> can have the property attribute on the right.
Object bean = getbean (beandefine. GETID (); // obtain the bean instance id
If (bean! = NULL ){
Try {
// If the property retrieved from <property> (stored in the Name field) is in the property (FIELD) of the class corresponding to <bean>, we must ensure that
// <Property name = "property" ......> The "attribute" in has a corresponding definition in the class pointed to by <bean>

// Obtain the description of all attributes of the bean class (that is, all fields defined by the bean class)
PropertyDescriptor [] ps = Introspector. getBeanInfo (bean. getClass (). getPropertyDescriptors ();

For (PropertyDefinition property: beanDefine. getPropertys () {// a bean can have multiple <property>
// PropertyDescriptor contains many fields to find the fields corresponding to <property name = "property">
For (PropertyDescriptor propertyDes: ps) {// propertyDes is the description of the definition field pointed to by <bean>
System. out. println ("ps" + propertyDes. getName ());
// If the property name field is defined in <bean>, inject
If (property. getName (). equals (propertyDes. getName ())){
// Depending on the ref attribute in propety

// Obtain the property of the value corresponding to the name attribute of the property attribute of the current Bean class (here it refers to the persondao) setter Method
Method setter = propertydes. getwritemethod ();
// Obtain the corresponding ref class instance
If (setter! = NULL ){
Object value = sinletons. Get (property. getref ());
Setter. setaccessible (true); // make the private method transparent
Setter. Invoke (bean, value );
}

Break; // find the corresponding attribute. Do not compare other attributes.
}
}
}
} Catch (exception ex ){
Logger. getlogger (sglclasspathxmlapplicationcontext. Class. getname (). Log (level. Severe, null, ex );
}
}
}
}
}

 

2. PersonDao. java (Interface Program)

 

Package com. sgl. dao;
Public interface PersonDao {

Void add ();

}

 

3. PersonDaoBean. java (interface layer Implementation Program)
Package com. sgl. dao. imp;
Import com. sgl. dao. PersonDao;
Public class PersonDaoBean implements PersonDao {
Public void add (){
System. out. println ("execute the add () method in PersonDaoBean ");
}

}

4. PersonService. java (service layer interface)

Package com. sgl;
Public interface PersonService {

Void save ();

Void save2 ();

}

 

 

5. PersonServiceBean. java (business layer Implementation Program)

Package com. sgl. imp;
Import com. sgl. PersonService;
Import com. sgl. dao. PersonDao;

Public class PersonServiceBean implements PersonService {
Private PersonDao personDao;

Public void save (){
System. out. println ("I am the save () method in PersonServiceBean ");
PersonDao. add ();
}

 

Public void save2 (){
System. out. println ("this is the Save2 method in PersonServiceBean ");
}

Public void setPersonDao (PersonDao personDao ){
This. personDao = personDao;
}

}

 

6. In the configuration file, class encapsulation of corresponding properties (id, class, and property)

 

1) BeanDefinition. java

Package sgl. spring. principle;

Import java. util. ArrayList;
Import java. util. List;

Public class BeanDefinition {
Private String id;
Private String className;
Private List <PropertyDefinition> propertys = new ArrayList <PropertyDefinition> ();

Public BeanDefinition (){
}
Public BeanDefinition (String id, String className ){
This. id = id;
This. className = className;
}


Public String getId (){
Return id;
}

Public void setId (String id ){
This. id = id;
}

Public String getClassName (){
Return className;
}
Public void setClassName (String className ){
This. className = className;
}

Public List <PropertyDefinition> getPropertys (){
Return propertys;
}

Public void setpropertys (list <propertydefinition> propertys ){
This. propertys = propertys;
}
}

 

2) propertydefinition. Java (<property> definition)

Package SGL. Spring. principle;

Public class propertydefinition {
Private string name;
Private string ref;

Public propertydefinition (string name, string ref ){
This. Name = Name;
This. ref = ref;
}

Public propertydefinition (){
}

Public String getName (){
Return name;
}

Public void setName (String name ){
This. name = name;
}

Public String getRef (){
Return ref;
}

Public void setRef (String ref ){
This. ref = ref;
}

}

 

7. unit test file SglSpringTest. java, is a junit-4.x

 

 

Package junit. test;

Import com. sgl. PersonService;
Import org. junit. After;
Import org. junit. AfterClass;
Import org. junit. Before;
Import org. junit. BeforeClass;
Import org. junit. Test;
Import sgl. spring. principle. SglClassPathXmlApplicationContext;

Public class SglSpringTest {

Public SglSpringTest (){
}

@ BeforeClass
Public static void setUpClass () throws Exception {
}

@ AfterClass
Public static void tearDownClass () throws Exception {
}

@ Before
Public void setUp (){
}

@ After
Public void tearDown (){
}


@ Test
Public void instanceBeans (){
SglClassPathXmlApplicationContext ctx = new SglClassPathXmlApplicationContext ("beans. xml ");
// Test Control inversion, that is, the object created by the container
PersonService personService = (PersonService) ctx. getBean ("personService ");
PersonService. save2 ();
// Test Control reversal and dependency Injection
PersonService personService4 = (PersonService) ctx. getBean ("personService4 ");
PersonService4.save ();
}

}

 

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.