Spring framerwork入门实例(4.2.4)
Spring framerwork入门实例(4.2.4)
1、下载Spring framerwork
下载地址:http://maven.springframework.org/release/org/springframework/spring/
2、解压并在spring-framework-4.2.4.RELEASE\libs 找到如下JAR包:
spring-beans-4.2.4.RELEASE.jar
spring-context-4.2.4.RELEASE.jar
spring-core-4.2.4.RELEASE.jar
spring-expression-4.2.4.RELEASE.jar
commons-logging-1.1.3.jar//此jar文件是apache提供的日志包 http://pan.baidu.com/s/1sk42Dkh
3、创建java项目把以上jar文件复制到项目的src目录下
4、在src目录下创建bean.xml文件(也可以是applicationContext.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 xsi:schemaLocation="http://www.springframework.org/schema/beans 5 http://www.springframework.org/schema/beans/spring-beans-4.2.xsd"> 6 7 <bean id="user" class="com.entity.User"> 8 <!-- 依赖构造方法注入 --> 9 <!-- 10 <constructor-arg name="id" value="100" /> 11 <constructor-arg name="name" value="张三丰" /> 12 --> 13 <!-- 依赖setter注入 --> 14 <property name="id" value="20160126"></property> 15 <property name="name" value="Xsum"></property> 16 </bean> 17 </beans>
5、建立com.entity.User.java类
1 package com.entity; 2 3 public class User { 4 private int id; 5 private String name; 6 public int getId() { 7 return id; 8 } 9 public void setId(int id) { 10 this.id = id; 11 } 12 public String getName() { 13 return name; 14 } 15 public void setName(String name) { 16 this.name = name; 17 } 18 //依赖构造方法注入需添加构造方法 19 /*public User(int id, String name) { 20 super(); 21 this.id = id; 22 this.name = name; 23 } 24 public User() { 25 }*/ 26 }
6、建立com.test.Test.java类
1 package com.test; 2 3 import org.springframework.context.ApplicationContext; 4 import org.springframework.context.support.ClassPathXmlApplicationContext; 5 6 import com.entity.User; 7 8 public class Demo { 9 public static void main(String[] args) { 10 ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml"); 11 User user = (User)ctx.getBean("user"); 12 System.out.println("id="+user.getId()+"\t"+"name="+user.getName()); 13 } 14 15 }
运行结果:
id=100 name=Xsum
本文仅为个人学习笔记,如有错误请给予指点,谢谢!!!