Spring(2):Spring Ioc

1.下载spring-framework-3.2.0

完整包下载路径:

https://repo.spring.io/webapp/#/artifacts/browse/tree/Properties/libs-release-local/org/springframework/spring/3.2.0.RELEASE

或者,本Sample只需要四个包,下载路径:

https://files.cnblogs.com/files/xueyuangudiao/Spring_IoC.zip

 

2.下载Commons Logging

依赖Commons Logging,所以需要下载。

下载路径:

http://commons.apache.org/proper/commons-logging/download_logging.cgi

或者:https://files.cnblogs.com/files/xueyuangudiao/commons-logging-1.2-bin.zip

3.创建普通java项目

 

 4.将下载的jar导入到项目中

 

 5.编写一个model,这个model后面经通过依赖注入的方式来实例化。

 1 public class User {
 2     
 3     private String userName;
 4     private int age;
 5     
 6     public String getUserName() {
 7         return userName;
 8     }
 9     public void setUserName(String userName) {
10         this.userName = userName;
11     }
12     public int getAge() {
13         return age;
14     }
15     public void setAge(int age) {
16         this.age = age;
17     }
18     
19     @Override
20     public String toString() {
21         return "User [userName=" + userName + ", age=" + age + "]";
22     }
23 }

6.创建xml文件(springTest.xml),Spring将读取xml文件中的内容来明确类型与注入内容的对应关系

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="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:作为bean的代号,在代码中会用到;class:类名 -->
 8     <bean id="user" class="com.test.model.User">
 9         <!-- User类中的属性名,通过Spring实例化User时,会将value赋值给userName这个属性 -->
10         <property name="userName" value="李四"></property>
11         <property name="age" value="21"></property>
12     </bean>
13     
14 </beans>

7.创建HelloSpring类,其中main函数演示了依赖注入的方法与普通对象实例化方法的对比

 1 package com.test;
 2 
 3 import org.springframework.beans.factory.BeanFactory;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 
 6 import com.test.model.User;
 7 
 8 public class HelloSpring {
 9 
10     public static void main(String[] args) {
11 
12         // Spring写法
13         BeanFactory bf = new ClassPathXmlApplicationContext("springTest.xml");
14         User user2 = (User) bf.getBean("user");
15         System.out.println(user2);
16         
17         // 普通写法
18         User user1 = new User();
19         user1.setUserName("张三");
20         user1.setAge(20);
21         System.out.println(user1);
22 
23     }
24 }

执行结果:

User [userName=李四, age=21]
User [userName=张三, age=20]

 

8.整个代码结构

9.完整代码

https://files.cnblogs.com/files/xueyuangudiao/SpringTest2.zip

 

posted on 2018-04-05 18:30  abc0101  阅读(161)  评论(0编辑  收藏  举报

导航