The main injection methods are: attribute injection, construction injection, etc.
Let's look at an example:
1. Create a new interface Ipet
Package entities; Public Interface Ipet { public String getName (); Public void setName (String name); Public void sleep ();}
2. New two classes of dog and cat
Packageentities; Public classCatImplementsipet{//When the program runs,The properties of the cat are replaced by the attribute injection of the XML file PrivateString name = "Kitty"; Private intAge = 2; PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; } @Override Public voidsleep () {System.out.println (name+ "Little Cat Sleeps"); } }
Packageentities; Public classDogImplementsipet{ PublicString name; Public intAge ; PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; } //Constructing method Overloads PublicDog (String name,intAge ) { This. Name =name; This. Age =Age ; } Public voidsleep () {System.out.println (name+ "Puppy sleeps."); }}
3. Configuring the Beans.xml File
<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "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.xsd "> <!--point to the Cat class, using the value of the ID directly when called - <BeanID= "Pet1"class= "entities." Cat "> <!--Attribute Injection - < Propertyname= "Name"value= "Tom"></ Property> < Propertyname= "Age"value= "3"></ Property> </Bean> <BeanID= "Pet2"class= "entities." Dog "> <!--Construct method Injection - <Constructor-argname= "Name"value= "an"></Constructor-arg> <Constructor-argname= "Age"value= "4"></Constructor-arg> </Bean> </Beans>
4. Read the configuration file and run it
Packageentities;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext; Public classTest { Public Static voidMain (string[] args) {//Load configuration fileApplicationContext context =NewClasspathxmlapplicationcontext ("Beans.xml");
//read the ID of cat and Dog in the XML fileIpet Pet1 = (ipet) context.getbean ("Pet1"); Ipet Pet2= (Ipet) context.getbean ("Pet2"); Pet1.sleep (); Pet2.sleep (); }}
Operation Result:
<!-- attributes in the Cat class are replaced by the attributes of the XML file - Tom, the kitten is asleep.
<!-- read the constructor injection of an XML file, assigning a value to a property through a constructor in the dog class - an puppy sleeps.
Spring Dependency Injection (first, injection mode)