"Three big SSH framework" Spring Basics Part Two: Three ways spring relies on injection

Source: Internet
Author: User

controlled inversion (inversion of control) and dependency injection (Dependency injection):

Applying control inversion, when an object is created, it is passed to it by an external entity that controls all objects in the system by a reference to its dependent object. It can also be said that the dependency is injected into the object. So, control reversal is a reversal of this responsibility about how an object obtains a reference to the object he relies on.

For dependency injection, there are three ways:

1, using the property setter method injection

2. Using the constructor to inject

3. Use annotation Injection

Below we introduce the following three ways:

first, using the property setter method injection

First, we write a Personservice.java interface

Public interface Personservice {public abstract void Save ();
Then, we write an implementation class for this interface: Personservicebean.java

public class Personservicebean implements Personservice {private string Name;public string GetName () {return name;} public void SetName (String name) {this.name = name;} @Overridepublic void Save () {System.out.println (name);//persondao.add ();}}
We edit the Beans.xml file and configure the XML code for the IOC inversion container:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context"        xsi:schemalocation= "Http://www.springframework.org/schema/beans        Http://www.springframework.org/schema /beans/spring-beans-2.5.xsd        http://www.springframework.org/schema/context/        http Www.springframework.org/schema/context/spring-context-2.5.xsd    http://www.springframework.org/schema/ Context       http://www.springframework.org/schema/context/spring-context-2.5.xsd ">         <bean id=" Personservice "class=" Cn.itcast.service.impl.PersonServiceBean ">   <property name=" name "value=" Itcast "/ >   </bean></beans>
We wrote a bean and defined the class property, and in the bean we set the value for the "name" property: Itcast

Then, we write a test class: Springtest.java

public class Springtest {@BeforeClasspublic static void Setupbeforeclass () throws Exception {} @Testpublic void Instancesp Ring () {Abstractapplicationcontext CTX = new Classpathxmlapplicationcontext ("Beans.xml"); Personservice Personservice = (personservice) ctx.getbean ("Personservice");p Ersonservice.save (); Ctx.close ();}}
When we run, it will print out Itcast

Principle: Through Beans.xml We configure the IOC inversion container, and the configured properties are injected by setter methods. If there is no setter method will error.

second, using the constructor injection

First, we write a Persondao.java interface

Public interface Persondao {public void add ();
And this interface is implemented:

public class Persondaobean implements persondao{@Overridepublic void Add () {System.out.println ("I am the Add in Persondaobean ( ) method ");}}
Then, we write a Personservice.java interface:

Public interface Personservice {public  void Save ();}
And this interface is implemented:

public class Personservicebean implements Personservice {private Persondao persondao;private String name;public Personservicebean () {}public Personservicebean (Persondao Persondao, String name) {This.persondao = Persondao;this.name = name;} Public Persondao Getpersondao () {return persondao;} public void Setpersondao (Persondao persondao) {This.persondao = Persondao;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} @Overridepublic void Save () {Persondao.add (); SYSTEM.OUT.PRINTLN (name);//persondao.add ();}}
As you can see, in this implementation class, we introduce a property of type Persondao and a property of type string, and construct a constructor and setter, getter method that contains both parameters.

We then configure it in 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" xmlns:context= "Http://www.springframework.org/schema/context" xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-2.5.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/con Text/spring-context-2.5.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/ Context/spring-context-2.5.xsd "> <bean id=" Persondao "class=" Cn.itcast.dao.impl.PersonDaoBean "></bean > <bean name= "personservice" class= "Cn.itcast.service.impl.PersonServiceBean" > <constructor-arg index= " 0 "type=" Cn.itcast.dao.PersonDao "ref=" Persondao "></constructor-arg> <constructor-arg index=" 1 "value=" Itcast "/> </bean></beans>
As you can see, we have two beans configured:

The first bean is a dependent bean, and we need to rely on the class that the bean points to in the Personservicebean.java class

The second bean is the bean we're going to use, and in this bean we've configured two <constructor-arg> Tags: where index indicates the indexes, is the index of the parameters in the constructor, 0 represents the first argument; type indicates the types of this parameter, Ref indicates which class to rely on. The second does not have type and ref, because the string type does not need to specify the type, nor is it a dependent class, so the ref attribute is not required.


Then, we build a test class:

Package Junit.test;import static Org.junit.assert.*;import Org.junit.beforeclass;import Org.junit.test;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.abstractapplicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;import Cn.itcast.service.PersonService; public class Springtest {@BeforeClasspublic static void Setupbeforeclass () throws Exception {} @Testpublic void Instancesp Ring () {Abstractapplicationcontext CTX = new Classpathxmlapplicationcontext ("Beans.xml"); Personservice Personservice = (personservice) ctx.getbean ("Personservice");p Ersonservice.save (); Ctx.close ();}}
You can print out the contents of the Save () method in the Personservicebean.java class.


third, using annotation injection

The function of the @Resource is equivalent to @autowired, but @autowired is automatically injected by Bytype, and @resource is automatically injected by ByName by default. @Resource There are two attributes that are important, the name and type,spring the Name property of the @resource annotation to the bean's name, and the type attribute to the Bean's. So if you use the Name property, you use the ByName Auto-injection policy, and the Type property uses the Bytype auto-injection policy. If neither name nor the type attribute is specified, the ByName auto-injection policy is used through the reflection mechanism.
@Resource Assembly Order
1. If name and type are specified at the same time, the uniquely matched bean is found from the spring context to assemble, and an exception is thrown if it is not found
2. If name is specified, a bean matching the name (ID) from the context is assembled, and an exception is thrown if it is not found
3. If the type is specified, an exception is thrown when the unique bean matching the match is found in the context, cannot be found, or multiple occurrences are found
4. If neither name is specified and type is not specified, the assembly is automatically byname; if there is no match, the fallback is a match for the original type, and if the match is automatically assembled;
Here are just a few examples of using @resource:

The code is the same as above, just Personservicebean.java changed:

public class Personservicebean implements Personservice {@Resource (name= "Persondao") private Persondao Persondao; Private String name;public Persondao Getpersondao () {return persondao;} public void Setpersondao (Persondao persondao) {This.persondao = Persondao;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} @Overridepublic void Save () {Persondao.add ();}}
As you can see, we have added @resource (name= "Persondao") in front of the private Persondao Persondao;

Then, let's look at the Beans.xml configuration file:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context"        xsi:schemalocation= "Http://www.springframework.org/schema/beans        Http://www.springframework.org/schema /beans/spring-beans-2.5.xsd        http://www.springframework.org/schema/context/        http Www.springframework.org/schema/context/spring-context-2.5.xsd ">         <context:annotation-config/>< Bean id= "Persondao" class= "Cn.itcast.dao.impl.PersonDaoBean" ></bean>   <bean id= "Personservice" class= "Cn.itcast.service.impl.PersonServiceBean" ></bean>   </beans>
We've added a few lines of code:

xmlns:context= "Http://www.springframework.org/schema/context" Http://www.springframework.org/schema/context        http://www.springframework.org/schema/context/spring-context-2.5.xsd

Then, we run the test class and we can print it out.















"Three big SSH framework" Spring Basics Part Two: Three ways spring relies on injection

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.