1. Download spring-framework-3.2.0
Full package Download Path:
Https://repo.spring.io/webapp/#/artifacts/browse/tree/Properties/libs-release-local/org/springframework/spring /3.2.0.release
Or, this sample only needs four packages, download the path:
Https://files.cnblogs.com/files/xueyuangudiao/Spring_IoC.zip
2. Download Commons Logging
Rely on commons Logging, so download required.
Download path:
http://commons.apache.org/proper/commons-logging/download_logging.cgi
Or: Https://files.cnblogs.com/files/xueyuangudiao/commons-logging-1.2-bin.zip
3. Create a generic Java project
4. Import the downloaded jar into the project
5. Write a model that is later instantiated by a dependency injection method.
1 Public classUser {2 3 PrivateString UserName;4 Private intAge ;5 6 PublicString GetUserName () {7 returnUserName;8 }9 Public voidsetusername (String userName) {Ten This. UserName =UserName; One } A Public intGetage () { - returnAge ; - } the Public voidSetage (intAge ) { - This. Age =Age ; - } - + @Override - PublicString toString () { + return"User [username=" + UserName + ", age=" + Age + "]"; A } at}
6. Create an XML file (Springtest.xml), and spring will read the contents of the XML file to clarify the correspondence between the type and injected content
1 <?XML version= "1.0" encoding= "UTF-8"?>2 <Beansxmlns= "Http://www.springframework.org/schema/beans"3 Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"4 xmlns:p= "http://www.springframework.org/schema/p"5 xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" >6 7 <!--ID: Used as the code name of the Bean; class: -8 <BeanID= "User"class= "Com.test.model.User">9 <!--A property name in the user class that, when instantiated by spring, assigns value to the Username property -Ten < Propertyname= "UserName"value= "John Doe"></ Property> One < Propertyname= "Age"value= "+"></ Property> A </Bean> - - </Beans>
7. Create the Hellospring class, where the main function demonstrates the contrast between the method of dependency injection and the normal object instantiation method
1 Packagecom.test;2 3 Importorg.springframework.beans.factory.BeanFactory;4 ImportOrg.springframework.context.support.ClassPathXmlApplicationContext;5 6 ImportCom.test.model.User;7 8 Public classhellospring {9 Ten Public Static voidMain (string[] args) { One A //Spring notation -Beanfactory BF =NewClasspathxmlapplicationcontext ("Springtest.xml"); -User User2 = (user) Bf.getbean ("User"); the System.out.println (user2); - - //General Wording -User user1 =NewUser (); +User1.setusername ("Zhang San"); -User1.setage (20); + System.out.println (user1); A at } -}
Execution Result:
User [username= John Doe, age=21]
User [Username= Zhang San, age=20]
8. Entire code structure
9. Complete code
Https://files.cnblogs.com/files/xueyuangudiao/SpringTest2.zip
Spring (2): Spring Ioc