Spring基本应用

一.Spring概述

1.什么是Spring?
是一个分层的javase/javaee的轻量级开源框架,是以IOC(Inverse of Control 控制反转)和AOP(Aspect Oriented Programming 面向切面编程)为内核,使用javaBean来完成工作。

2.Spring框架的优点?
1.非侵入式设计
2.方便解耦、简化开发
3.支持AOP
4.支持声明式事务处理
5.方便程序测试
6.方便集成各种优秀框架
7.降低Java EE API的使用难度

3.Spring体系结构
采用的
采用的是分层结构,大致分为四大板块Data Access,web,Contsiner和test.

二.Spring核心容器(Core Container)

Spring为我们提供了两种核心容器:
1.BeanFactory
基本语法格式为;
BeanFactory beanFactory = new XmlBeanFactory(new FileSystemResource(“F: /applicationContext.xml”));

注解:这种在开发中并不多用,读者只需了解下。

2.ApplicationContext
ApplicationContext是BeanFactory的子接口,是另一种常用的Spring核心容器。它由org.springframework.context.ApplicationContext接口定义,不仅包含了BeanFactory的所有功能,还添加了对国际化、资源访问、事件传播等方面的支持。创建ApplicationContext接口实例,通常采用两种方法,具体如下:
1.通过ClassPathXmlApplicationContext创建
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext(String configLocation);

这里是引用
String 指的是名称,configLocation指的是位置。
这是我们常用的。
ClassPathXmlApplicationContext会从类路径classPath中寻找指定的XML配置文件,找到并装载完成ApplicationContext的实例化工作。

2.通过FileSystemXmlApplicationContext创建
ApplicationContext applicationContext =
new FileSystemXmlApplicationContext(String configLocation);

这里是引用
FileSystemXmlApplicationContext会从指定的文件系统路径(绝对路径)中寻找指定的XML配置文件,找到并装载完成ApplicationContext的实例化工作。

在Java项目中,会通过ClassPathXmlApplicationContext类来实例化ApplicationContext容器。

 <context-param>
               <param-name>contextConfigLocation</param-name> 
               <param-value>
                          classpath:spring/applicationContext.xml
               </param-value>
       </context-param> 
       <listener>
               <listener-class>
                         org.springframework.web.context.ContextLoaderListener
               </listener-class>
       </listener>

创建Spring容器后,就可以获取Spring容器中的Bean。Spring获取Bean的实例通常采用以下两种方法:
1.Object getBean(String name);
根据容器中Bean的id或name来获取指定的Bean,获取之后需要进行强制类型转换。
2. T getBean(Class requiredType);
根据类的类型来获取Bean的实例。由于此方法为泛型方法,因此在获取Bean之后不需要进行强制类型转换。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值