spring快速入门
① spring是什么?
Struts是web框架(jsp/action/actionform)
hibernate是orm框架(对象和关系映射框架),处于持久层
spring是容器框架,用于配置bean,并维护bean之间关系的一种框架
在spring中有一个非常重要的概念,bean的概念很大
bean(是Java中的任何一种对象,Javabean/servie/action/数据源/dao,ioc(控制反转inverse of control),di(dependency injection)依赖注入 )
画一个层次框架图:
pojo(Java简单对象)
快速入门
开发一个spring项目
1、引入spring的开发包(最小配置spring.jar该包把常用的jar都包括了、还要一个写日志的包common-logging.jar)
2、创建spring的一个核心文件applicationContext.xml,[hibernate有核心hibernate.cfg.xml,struts核心文件struts-config.xml],该文件一般放在src目录下
xml中规范文件2.5以前用的是dtd,2.5以后用的是->xsd schmea文件,用来约束文件中的元素,子元素以及出现的顺序。
applicationContext.xml中引入xsd文件:可以从给出的案例中拷贝一份。
3、配置bean
4、在Test.java中使用
项目目录结构:
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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!-- 在容器文件中配置bean(service/dao/domain/action/数据源) --> <!-- bean元素的作用是,当我们的spring框架加载的时候,spring就会去看这里面有没有bean,如果有这个bean spring就会自动创建这个bean对象,并且将其装在到内存里面去 --> <!-- 类似于:Userservice userService = new UserService(); id号是和对象的变量名对应的,如果id号为litao,则这句话的含义为 UserService litao = new UserService(); property为属性值,name为注入这个属性,等价于 userService.setName("小明");set方法必须写否则注入不进去 --> <bean id="userService" class="com.service.UserService"> <!-- 这里体现了容器的特点,配置bean并注入属性,体现出注入的概念 --> <property name="name"> <value>小明</value> </property> </bean> </beans>
UserService.java
package com.service; public class UserService { public String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public void sayHello(){ System.out.println("hello " + name); } }
Test.java
package com.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.service.UserService; public class Test { public static void main(String[] args){ //我们先使用传统方法,来调用UserService的sayHello方法 UserService userService = new UserService(); userService.setName("小明"); userService.sayHello(); //我现在来使用spring来完成上面的任务 //1.得到spring的applicationContext对象(容器对象) //通过类路径加载文件,这个对象就对象applicationContext.xml文件 ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); UserService us = (UserService)ac.getBean("userService"); us.sayHello(); } }