In a previous blog about the principles of spring's IOC container, the IOC, which controls the reversal, is largely dependent on injection. Dependency injection means that the dependent object is not made by itself, but is injected in another way like an injection. In fact, both control inversion and dependency injection show that spring uses dynamic, flexible ways to manage objects.
Spring's dependency injection has virtually no requirement for callers and callers to fully support the management of dependencies between Pojo. There are several ways to inject:
1. Setter Injection
Because for JavaBean, we can change the object and get the properties of the object individually by setter and getter methods. So as long as the current object adds setter methods for the properties of its dependent object, it is possible to set the corresponding dependent object into the injected object by setter method. For example, the following code:
. Person Interface
Package com.tgb.depency;/** * Define person interface * @author Mingxuanyun * */public interface Person {//define a way to eat public void ea Tsomething (); Define a personal information method public String personInfo ();}
. Eat interface
Package Com.tgb.depency;public interface Eat {//define an apple-eating method public String eatapple ();}
. The implementation class for person
/** * Person Implementation class * @author Mingxuanyun */public class Huohuo implements Person{private Eat eat;//default constructor public Huohuo () {}pu Blic Eat geteat () {return Eat;} public void Seteat (Eat Eat) {this.eat = Eat;} The method of realizing the person eats @overridepublic void eatsomething () {System.out.println (Eat.eatapple ());} @Overridepublic String PersonInfo () {return null;}}
. Implementation class of Eat
/** * Big Mouth stuttering * @author Mingxuanyun */public class Widemoutheat implements Eat {@Overridepublic String eatapple () {return "large It's rude to eat apples in your mouth!!! ";}}
. configuration file , which organizes the person instance and the Eat instance together
<!--setter Injection test instance--><bean id= "Huohuo" class= "Com.tgb.depencyimpl.Huohuo" ><property name= "eat" ref= " Widemoutheat "></property></bean><bean id=" Widemoutheat "class=" Com.tgb.depencyimpl.WideMouthEat "></bean>
As you can see from the above example, spring puts the dependency between the bean and the bean in the configuration file, rather than in the code. With the configuration file, spring accurately injects each attribute into each bean. The Name property in <bean> is an alias for the class attribute, which refers to the real implementation class (the full name of the class). Spring automatically takes over the property element definition in each bean. Spring then executes the parameterless constructor, and after creating the default bean, calls the corresponding setter method to inject the property value into the program.
. Main program
public class Settertest {public static void main (string[] args) {//Instantiate spring context ApplicationContext CTX = new Filesystemxml ApplicationContext ("Bean.xml");//cast interface type person person = (person) ctx.getbean ("Huohuo");// The Eatsomething method that executes person person.eatsomething ();}}
. Run the result output:
It's rude to eat apples with a big mouth!!!
Description: The main program calls the Person.eatsomething method, which requires an instance of eat in the body, but there is no place in the main program for a eat instance of the person instance, and the eat instance is injected dynamically by spring during runtime. The person instance does not need to know the specific implementation and creation process of the Eat instance. When the program runs to the Eat instance, spring automatically creates the eat instance and injects it to its caller, and the person instance runs to the eat instance when it is required to automatically generate the Eat instance.
What good is this? If we need another eat implementation class to use for the person class. Neither person nor its implementation classes need to be changed. You only need to add a eat implementation class and configure it in the configuration file.
For example, increase the Eat implementation class Chewslowlyeat
Import Com.tgb.depency.eat;public class Chewslowlyeat implements Eat {@Overridepublic String eatapple () {return] An example of a lady who is eating slowly!! ";}}
To Modify a configuration file:
<bean id= "Huohuo" class= "Com.tgb.depencyimpl.Huohuo" > <property name= "Eat" ref= "Chewslowlyeat" ></ Property></bean><bean id= "Chewslowlyeat" class= "Com.tgb.depencyimpl.ChewslowlyEat" ></bean>
Output Result:
An example of a lady who is eating slowly!!
2. Constructor injection
Refers to a list of parameters that are injected into an object by declaring a dependent object in its constructor.
Defines a person implementation class for constructor injection
/** * Constructor Injection test * @author Mingxuanyun */public class Yunyun implements person{private String userName; Private String kind; Private Eat Eat; Default constructor method public Yunyun () {}; Constructs the injected required with the parameter constructor public Yunyun (Eat eat,string username,string kind) {this.eat = Eat; This.username = UserName; This.kind = kind; } @Override Public String PersonInfo () {return userName + "forever" + Kind + "year" + "----" + eat.eatapple (); } @Override public void eatsomething () {//TODO auto-generated method stub}}
When constructing an Yunyun instance, create a eat of three member variables, username, kind, and object types. However, the setter method is not set. When constructing a person instance, spring injects the dependent eat instance into the person instance and assigns a value to the two member variables. The configuration file for the construction injection is as follows:
. XML configuration file
<!--constructor Injection configuration instance--> <bean id= "Yunyun" class= "Com.tgb.depencyimpl.Yunyun" > <constructor-arg index= "0" ref= " Chewslowlyeat "></constructor-arg> <constructor-arg index=" 1 "> <value> Zhu </value> </constructor-arg> <constructor-arg index= "2" > <value>18</value> </constructor-arg> </bean> <bean id= "chewslowlyeat" class= "Com.tgb.depencyimpl.ChewslowlyEat"/>
In the configuration file, use the <constructor-arg> tag instead of the <property> form. The ref attribute points to the Name property of the other <bean> tag. Because we may pass in multiple types of consistent construction parameters. So you can use type and index to determine which constructor we are using.
. Main program
public class Constructortest {public static void main (string[] args) {String fileName = "Bean.xml"; ApplicationContext ac = new Filesystemxmlapplicationcontext (fileName); Get an example yunyun Yunyun = (Yunyun) Ac.getbean ("Yunyun"); System.out.println (Yunyun.personinfo ());} }
Output Result:
Zhu Forever 18 years old to eat lady's model!!
3. Static Factory Method Injection
Refers to the method of calling a static factory to get the object you want.
. Define a Userdao class
public class Userdao {public static Userdao getinstance () {return new Userdao ("Static Factory Method"); Private String name= ""; Public Userdao (String name) {this.name = name;} public void Create () {System.out.println ("Create user from-" + name);}}
. Define a Usermanager class
Import Com.tgb.depency.userdao;public class Usermanager {//Inject Userdao object private Userdao Userdao; public void CreateUser () {userdao.create ();} public void Setuserdao (Userdao userdao) {This.userdao = Userdao;} Public Userdao Getuserdao () {return Userdao;}}
. XML configuration file
<!--static Factory method injection--><bean name= "Usermanager" class= "Com.tgb.depencyimpl.UserManager" ><property name= " Userdao "ref=" Userdao "></property></bean><bean name=" Userdao "class=" Com.tgb.depency.UserDao " Factory-method= "GetInstance" ></bean>
Factory-menthod defines the Userdao. The bean uses the GetInstance method of the Userdao class to create its own instance.
. Main program
public class Staticfactorytest {public static void main (string[] args) {String fileName = "Bean.xml"; ApplicationContext ac = new Filesystemxmlapplicationcontext (fileName); Usermanager Usermanager = (usermanager) ac.getbean ("Usermanager"); Usermanager.createuser ();}}
Output Result:
Create User From-static factory method
Summary: When we originally learned three layers, the UI layer called the BLL, the BLL called the DAO layer. Although the interface layer is abstracted from each layer, the interface is called. But in new, the point is the concrete implementation. Now spring effectively manages the invocation of objects between layers. Whether the action invokes the Services object or the services call the DAO object, spring organizes them together in a loosely coupled manner. There is no need to care about the specific implementation between the objects, and how to create, fully interface-oriented programming.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Spring's IOC container-dependency Injection