spring特点: 1.轻量级:与EJB对比,依赖资源少,销毁的资源少 2.分层:一站式,每一个层都提供的解决方案
spring 核心:ioc 控制反转和AOP面向切面编程
spring 优点:
1.方便解耦,简化开发:spring 就是一个大工厂,可以将所有对象的创建和依赖关系维护,交给spring管理。2.aop切面编程spring 提供面向切面编程,可以方便的实现对程序进行权限拦截,运行监控等功能。3.声明式事务的支持只需要通过配置就可以完成对事物的管理,而无需手动编程。4.方便程序的测试spring 对junit 支持,可以通过注解方便的测试spring 程序。5.方便集成各种优秀框架spring 不排斥各种优秀的开源框架,其内部提供了对各种优秀框架的直接支持。6.降低javaEE api的使用难度spring 对JavaEE 开发中非常难用的API(jdbc,javaMail,远程调用)都提供了封装,使这些API应用难度大大降低。1.项目依赖有:1个依赖+4个核心。分别为:
com.springsource.org.apache.commons.logging-1.1.1.jar 依赖spring-beans-3.2.0.RELEASE.jarspring-context-3.2.0.RELEASE.jarspring-core-3.2.0.RELEASE.jarspring-expression-3.2.0.RELEASE.jar 约定 1配置文件一般在classpath 下,开发中常用applicationContext.xml。内容添加schema约束21.依赖:一个对象需要使用另一个对象 2.注入:通过setter 方法进行另一个对象实例设置。
//方式一:接口 = 实现类 private Dao dao = new DaoImpl(); //方式二:接口+ setter private Dao dao;
public void setDao(Dao dao){ this.dao = dao; }
//方式 三:spring 注入:
<!--配置service 配置需要创建的对象 --> <bean id="userService" class="service.impl.UserServiceImpl"> <!--用于属性注入,name: bean 的属性名,通过setter方法获得,ref:另一个bean的id的引用 --> <property name="userDao" ref="userDao"></property> </bean> <bean id ="userDao" class="dao.UserDao"></bean>
注解:程序调用service 的时候,会看有没有引用,如果有引用,先实例化引用[dao 层],再实例化自己[service层],也就可以正常调用了。
String xmlPath = "beans.xml"; ApplicationContext context = new ClassPathXmlApplicationContext(xmlPath); //2获得内容 --不需要自己new,都是从spring容器获得 UserService userService = (UserService) context.getBean("userService"); Users user = new Users(); user.setId(1); user.setName("张洁"); int result = userService.save(user); System.out.println("application得到的结果:"+result);
添加myeclipse schema
复制:http://www.springframework.org/schema/beans/spring-beans.xsd ---window---preferences --- xml catalog --- add---file system---
BeanFactory: 这个一个工厂类,用于生成任意bean。采取延迟加载,第一次getBean 时才会初始化Bean。 ApplicationContext: 是BeanFactory 的子接口,BeanFactory的扩展,功能更强大。 1.国际化处理 2.事件传递 3.Bean 自动装配 4.各种不同应用层的Context 实现。 ClassPathXmlApplicationContext:用于加载classpath(类路径,src)下的xml。 FileSystemXmlApplicationContext:用于加载指定盘符下的xml文件
