spring框架基本搭建及使用

来源:互联网 发布:windows蓝牙抓包工具 编辑:程序博客网 时间:2024/05/16 03:35

简介

Spring是一个一款开发web项目的轻量级框架,包括核心容器、应用上下文(context)模块、AOP模块、Web模块、SpringMVC模块、Dao模块和ORM模块,有控制反转(IOC)、面向切面(AOP)等功能。

这里写图片描述

本文只介绍spring的基本搭建及使用

jar包

下载地址
使用的是 spring-framework-4.2.5.BUILD-SNAPSHOT

这里写图片描述

导入基本jar包

xml文件配置

bean.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"               xmlns:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="http://www.springframework.org/schema/beans                         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd                            http://www.springframework.org/schema/context                                                   http://www.springframework.org/schema/context/spring-context-3.0.xsd">          <bean id="person" class="cn.xiedacon.test.domain.Person" scope="prototype" /></beans>

简单demo

Person类

package cn.xiedacon.test.domain;import java.util.Date;public class Person {    private String name = "张三";    private Date birthday = new Date();    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Date getBirthday() {        return birthday;    }    public void setBirthday(Date birthday) {        this.birthday = birthday;    }    @Override    public String toString() {        return "Person [name=" + name + ", birthday=" + birthday + "]";    }}

测试类

package cn.xiedacon.test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import cn.xiedacon.test.domain.Person;public class Test1 {    public static void main(String[] args) {        ApplicationContext context = new ClassPathXmlApplicationContext(                "beans.xml");        Person person = (Person) context.getBean(Person.class);        System.out.println(person);    }}

执行main方法后,输出结果

这里写图片描述

以上就是spring框架的基本搭建与使用。

在web应用中,一般不会使用ClassPathXmlApplicationContext类来获取spring容器,而是将spring容器配置在web.xml文件中

<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">    <display-name></display-name>    <welcome-file-list>        <welcome-file>index.jsp</welcome-file>    </welcome-file-list>    <!-- spring核心监听器 -->    <listener>        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener>    <!--- spring配置文件路径 -->    <context-param>        <param-name>contextConfigLocation</param-name>        <param-value>classpath:spring/applicationContext*</param-value>    </context-param></web-app>

在web应用启动时,初始化容器,通过配置文件或注解实现依赖注入(DI)等。

0 0