java 搭建spring核心框架

来源:互联网 发布:yy网络直播间 编辑:程序博客网 时间:2024/06/06 03:46

1、需要5个引用包,分别是

  commons-logging-1.1.3.jar           日志

spring-beans-3.2.5.RELEASE.jar       bean节点

spring-context-3.2.5.RELEASE.jar      spring上下文节点

spring-core-3.2.5.RELEASE.jar        spring核心功能

spring-expression-3.2.5.RELEASE.jar    spring表达式相关表

下载包的地址:http://repo.springsource.org/libs-release-local/org/springframework/spring/3.2.5.RELEASE/spring-framework-3.2.5.RELEASE-dist.zip(此地址缺一个日志包)

2、新建applicationContext.xml文件

步骤如下:包=》右键=》New=》Xml(Basic Themplate)=>applicationContext.xml文件。

  约束参考:                  
spring-framework-3.2.5.RELEASE\docs\spring-framework-reference\htmlsingle\index.html
文件里Ctrl+F 搜xmlns;

        

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="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">         </beans>

3、src右键=》新建一个类AppCommon.java文件

内容:

    

public class AppCommon {@Testpublic void testIOC() {//得到IOC对象ApplicationContext cnApplicationContext=new ClassPathXmlApplicationContext("路径+applicationContext.xml");}}

4、新建一个bean文件=》src右键=》new=》class=>User.java

public class User {private int id;private String userName;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}                      }

5、再applicationContext.xml文件中加入

    

 <?xml version="1.0" encoding="UTF-8"?>   <beans xmlns="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">                      <!-- IOC配置都放在这里,要配置的所有对象都放在这里 -->           <!--[1]scope="singleton" 默认值及单例  ,service/dao/工具类 【2】 scope="prototype" 多例 action对象 -->           <bean id="user" class=" 包名+User" scope="singleton"></bean></bean>
6、再AppCommon.java文件

  

import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.springframework.core.io.ClassPathResource;public class AppComon {@Testpublic void testIOC() {//得到IOC对象ApplicationContext applicationContext=new ClassPathXmlApplicationContext("路径+applicationContext.xml");//从容器中获取beanUser user=(User)applicationContext.getBean("user");System.out.println(user);}}
右键run as =>JUnit Test

运行出来结果说明spring框架搭建通了。




原创粉丝点击