Spring notes (ii): Injection and assembly of Ioc

Source: Internet
Author: User

Spring notes (ii): Injection and assembly of Ioc

I. Principles of Spring dependency Injection


II. Implementation of dependency Injection

(1) object Injection

1. Simple property Injection

1) source code

Package main.java.com. spring. ioc. base. dao. impl; import main.java.com. spring. ioc. base. dao. personDao;/*** PersonDiDaoImpl * @ title * @ desc * @ author SAM-SHO * @ Dec 28,201 4 */public class PersonDiDaoImpl implements PersonDao {@ Overridepublic void save () {System. out. println ("the save () method of PersonDiDaoImpl is called ");}}

package main.java.com.spring.ioc.base.service.impl;import main.java.com.spring.ioc.base.dao.PersonDao;import main.java.com.spring.ioc.base.service.PersonService;/** * PersonDiServiceImpl * @desc  * @author SAM-SHO * @Dec 25, 2014 */public class PersonDiServiceImpl implements PersonService {private PersonDao personDao;@Overridepublic void save() {personDao.save();}public PersonDao getPersonDao() {return personDao;}public void setPersonDao(PersonDao personDao) {this.personDao = personDao;}}

2) configuration file

 
 
 
 
 
  
  
 

3) test

@ Testpublic void BeanDISucess () {// 1-object injection // 1-1 simple property injection ref attribute (recommended) ApplicationContext cxt = new ClassPathXmlApplicationContext ("application-di-Context.xml "); personService tPersonService = cxt. getBean ("PersonDiService", PersonDiServiceImpl. class); // use the interface to receive tPersonService. save (); // [Output]: The save () method of PersonDiDaoImpl is called}


4) Analysis:

① Use key elements

②. Name: the name must be the same as the XXX name of the setXXX () method in the class. That is, setPersonDao is consistent with name = "personDao.

③ Ref: point to the defined Bean to be injected.


2. Internal Bean Injection

1) source code

2) configuration file

 
 
  
   
  
 

3) test

// 1-2 use the internal Bean property injection (the injected Bean cannot be reused) PersonService tPersonService2 = cxt. getBean ("PersonDiService2", PersonDiServiceImpl. class); // use the interface to receive tPersonService2.save (); // [Output]: The save () method of PersonDiDaoImpl is called.

4) Analysis: Internal Bean injection refers to defining the beans to be injected into the injected bean. In fact, this does not achieve the effect of repeated use.


(2) Basic Type Injection

1. String Injection

1) source code: add the property name in PersonDiServiceImpl. Modify the save () method

private String name;public String getName() {return name;}public void setName(String name) {this.name = name;}

@ Overridepublic void save () {System. out. println ("the value of the injected simple attribute is:" + name); personDao. save ();}

2) configuration file

 
 
  
  
 

3) test

// 2-injection of the basic type PersonService tPersonService3 = cxt. getBean ("personDiService3", PersonDiServiceImpl. class); // use the interface to receive tPersonService3.save (); // [Output]: the value of the simple property injected is: SAM-SHO


2. Date Injection

1) source code: add the Date type attribute and modify the save () method.

Private Date date; public Date getDate () {return date;} public void setDate (Date date) {this. date = date ;}@ Overridepublic void save () {System. out. println ("the injected Date attribute value is:" + date); System. out. println ("the injected simple attribute value is:" + name); personDao. save ();}

2) configuration file: Use SimpleDateFormat Injection

         
      
 
 
  
   
                   
                
   
  
 

3) test

// 2-2 Date injection PersonService tPersonService4 = cxt. getBean ("personDiService4", PersonDiServiceImpl. class); // use the interface to receive tPersonService4.save (); // [Output]: The injected Date attribute value is: Thu Jan 01 00:00:00 CST 2015

4) Analysis: Use the instance factory method of SimpleDateFormat parse () to initialize its Bean, and then inject



(3) injection of various Collection types

1. List set type

1) source code: add the list attribute

// List collection type private List
 
  
Lists = new ArrayList
  
   
(); Public List
   
    
GetLists () {return lists;} public void setLists (List
    
     
Lists) {this. lists = lists ;}
    
   
  
 

2) configuration file

 
 
  
  
  
   
    
     
1st List values
    
    
     
2nd List values
    
    
     
3rd List values
    
   
  
 

3) test

// 3-set-type injection of PersonDiServiceImpl tPersonDiService5 = cxt. getBean ("personDiService5", PersonDiServiceImpl. class); // injection of the 3-1 List set for (String strValue: tPersonDiService5.getLists () {System. out. println ("List set injection value:" + strValue);} System. out. println ("--------------------------");


4) Analysis: Use Tag


2. Set type

1) source code

// Set collection type private Set
 
  
Sets = new HashSet
  
   
(); Public Set
   
    
GetSets () {return sets;} public void setSets (Set
    
     
Sets) {this. sets = sets ;}
    
   
  
 

2) configuration file

 
 
  
   
    
Set Value yi
   
   
    
Er set Value
   
   
    
Set Value of the nth san
   
  
 


3) test

PersonDiServiceImpl tPersonDiService5 = cxt. getBean ("personDiService5", PersonDiServiceImpl. class); // 3-2 set injection for (String strValue: tPersonDiService5.getSets () {System. out. println ("Set injection value:" + strValue );}

4) Analysis: Tag


3. Properties set type

1) source code

// Properties set type private Properties properties = new Properties (); public Properties getProperties () {return properties;} public void setProperties (Properties properties) {this. properties = properties ;}

2) configuration file

 
 
  
   
    
1-properties-Value
   
   
    
2-properties-Value
   
   
    
3-properties-Value
   
  
 


3) test

ApplicationContext cxt = new ClassPathXmlApplicationContext ("application-di-Context.xml"); PersonDiServiceImpl tPersonDiService5 = cxt. getBean ("personDiService5", PersonDiServiceImpl. class); // injection of the 3-3 Properties set for (Object key: tPersonDiService5.getProperties (). keySet () {System. out. println ("Properties set injection value:" + tPersonDiService5.getProperties (). get (key ));}

4) Analysis: 1-properties-Value


4. Map set type

1) source code

// Map set type private Map
 
  
Maps = new HashMap
  
   
(); Public Map
   
    
GetMaps () {return maps;} public void setMaps (Map
    
     
Maps) {this. maps = maps ;}
    
   
  
 


2) configuration file

 
 
  
   
   
   
 

3) test

// 3-4 Map set injection (in fact, Map can also be implemented using the Properties configuration) for (String key: tPersonDiService5.getMaps (). keySet () {System. out. println ("Map set injection value:" + tPersonDiService5.getMaps (). get (key ));}


4) Analysis:


Iii. Method of dependency Injection

1. Property injection: an object exists in another object as a property, including the setter and getter methods.

1) source code

private PersonDao personDao;public PersonDao getPersonDao() {return personDao;}public void setPersonDao(PersonDao personDao) {this.personDao = personDao;}


2) configuration file

 
 
  
  
 

2. constructor Injection

1) source code

// The constructor must have no parameters. public PersonDiServiceImpl () {}// the constructor injects public PersonDiServiceImpl (PersonDao personDao, String name) {this. personDao = personDao; this. name = name ;}

2) configuration file

 
 
 
  
  
  

3) test

// 2-constructor-arg injection constructor // constructor-arg // constructor method ApplicationContext cxt = new ClassPathXmlApplicationContext ("application-di-Context.xml"); PersonService tPersonService = cxt. getBean ("personDiService7", PersonDiServiceImpl. class); // use the interface to receive tPersonService. save ();

[Output] // The value of the simple property injected is: constructor injection // The save () method of PersonDiDaoImpl is called.


4) Analysis

①, Label.

② There must be no construction method for parameters


3. Use Field Injection (for annotation)

1) java @ Resource (recommended)

2) @ Autowire of spring



Iv. annotation to complete Bean Injection


(1) Resource Annotation

1. Analyze the implementation principle of @ Resource Annotation

2. Implementation

1) source code

@Resourceprivate PersonDao personDao;public PersonDao getPersonDao() {return personDao;}public void setPersonDao(PersonDao personDao) {this.personDao = personDao;}

2) configuration file

 
 
  
 
 
 

3) test

ApplicationContext cxt = new ClassPathXmlApplicationContext ("application-di-annotation-Context.xml"); PersonService tPersonService = cxt. getBean ("personServiceImplAnnotation", PersonDIServiceImplAnnotation. class); // use the interface to receive tPersonService. save (); // [Output] the save () method of PersonDiDaoImplAnnocation is called

3. Analysis

1) The xml_Schema and . This configuration implicitly registers multiple processors AutowiredAnnotationBeanPostProcessor, CommonAnnotationBeanPostProcessor, PersistenceAnnotationBeanPostProcessor, and RequiredAnnotationBeanPostProcessor that parse the annotation.


2) @ Resource annotation needs to import common-annotations.jar. By default, name-based assembly is performed. If the name attribute is not specified, the data type is displayed if it cannot be found.

3) The two annotations can be placed on the property or setXXX method.


(2) @ Autowire Annotation

1. Implementation

1) source code

// By default, the dependent object must exist. If null is allowed, you can set it to required = false // @ Autowired (required = true) // @ Autowired @ Qualifier ("personDao") @ Autowiredprivate PersonDao personDao;


2. Analysis

1) @ Autowired is assembled by type by default. To use name assembly, use @ Qualifier ("personDao.

3. By default, the dependent object must exist. If the value is null, set required to false.


5. Automatic Assembly (not recommended)

(1) automatic assembly

1. xml configuration: Autowired
1) byType: assemble by attribute type, multiple matching Bean types, throwing an exception
2) byName: assemble by attribute name
3) constructor: constructor parameter type
4) autodetect: automatically determines through the introspection mechanism. If there is a default constructor, press byType.


(2) Instances

1. Configuration

 
 
 

2. Test

/** Automatic assembly * xml configuration: Autowired: * 1. byType: assemble by attribute type. If Multiple matching Bean types exist, an exception is thrown * 2. byName: assemble by attribute name * 3. constructor: constructor parameter type * 4. autodetect: automatically determined by introspection. If there is a default constructor, press byType. */PersonService tPersonService = cxt. getBean ("personServiceImplAnnotation1", PersonDIServiceImplAnnotation. class); // use the interface to receive tPersonService. save (); // [Output] the save () method of PersonDiDaoImplAnnocation is called


6. Spring automatically scans and manages beans

(1) automatic scanning: Using annotations to manage beans

1. Four Annotations:

1) @ Controller: The most common action, with @ Scope ("prototype ").

2) @ Service: Used for the service layer.

3) @ Repository: Used for the Dao layer.

4) @ Component: used for different annotations.


2. Configure the package to be scanned

 
 


3. @ PostConstruct: corresponds to the init-method, after which.

4. @ PreDestroy: destroy-method, before the container is closed.

(2) combination of automatic scanning and Annotation

1. Source Code:

@Servicepublic class PersonDIServiceImplAnnotation implements PersonService {@Resourceprivate PersonDao personDao;}

@ Repositorypublic class PersonDiDaoImplAnnocation implements PersonDao {@ Overridepublic void save () {System. out. println ("the save () method of PersonDiDaoImplAnnocation is called ");}}

2. Configuration:

  
 

1) No Bean configuration is required.

2) In addition, the parsing annotation configuration can be omitted when automatic scanning is used. Because the configuration annotation only implicitly registers multiple processors that parse the annotation, automatic scanning can achieve the same effect.

 

3. Test

// Automatically scan @ Testpublic void beanAutoScrean () {AbstractApplicationContext cxt = new ClassPathXmlApplicationContext ("application-di-annotation-Context.xml"); PersonService tPersonService = cxt. getBean ("personDIServiceImplAnnotation", PersonDIServiceImplAnnotation. class); // use the interface to receive // tPersonService. save (); tPersonService. save (); cxt. close ();}


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.