Spring框架的初步学习
- 降低组件之间的耦合度;
- 提供了很多服务,事务管理服务,spring core核心服务,持久化服务等等。事务管理方面,不需要我们手工控制事务,也需要手动的去处理事务的传播行为;
- 容器提供单例模式支持,不需要再编写实现代码;
- AOP技术,很容易实现权限拦截,运行期监控等功能;
- 提供了很多的辅助类,如JdbcTemplate,HibernateTemplate
- 提供了主流应用框架集成的支持,如hibernate,mybatis
- 解析配置的xml文件,获取到beans节点下面的bean
- 将bean装入集合,对外提供getBean方法,通过反射技术,Class.forName('xxx').newInstance()方法来获取到bean对象的实例
/**
* 读取xml配置文件
* @param filename
*/
private void readXML(String filename) {
SAXReader saxReader = new SAXReader();
Document document=null;
try{
URL xmlpath = this.getClass().getClassLoader().getResource(filename);
document = saxReader.read(xmlpath);
Map<String,String> nsMap = new HashMap<String,String>();
nsMap.put("ns","http://www.springframework.org/schema/beans");//加入命名空间
XPath xsub = document.createXPath("//ns:beans/ns:bean");//创建beans/bean查询路径
xsub.setNamespaceURIs(nsMap);//设置命名空间
List<Element> beans = xsub.selectNodes(document);//获取文档下所有bean节点
for(Element element: beans){
String id = element.attributeValue("id");//获取id属性值
String clazz = element.attributeValue("class"); //获取class属性值
BeanDefinition beanDefine = new BeanDefinition(id, clazz);
XPath propertySub = element.createXPath("ns:property");
propertySub.setNamespaceURIs(nsMap);
List<Element> propertiesElement = propertySub.selectNodes(element);
for (Element property : propertiesElement) {
String name = property.attributeValue("name");
String ref = property.attributeValue("ref");
String value = property.attributeValue("value");
// System.out.println(name + "==" + ref);
beanDefine.getProperties().add(new PropertyDefinition(name, ref,value));
}
beanDefines.add(beanDefine);
}
}catch(Exception e){
e.printStackTrace();
}
}
/**
* 完成bean的实例化
*/
private void instanceBeans() {
for(BeanDefinition beanDefinition : beanDefines){
try {
if(beanDefinition.getClassName()!=null && !"".equals(beanDefinition.getClassName().trim()))
sigletons.put(beanDefinition.getId(), Class.forName(beanDefinition.getClassName()).newInstance());
} catch (Exception e) {
e.printStackTrace();
}
} }
/**
* 为bean对象的属性注入值
*/
private void injectObject() {
for(BeanDefinition beanDefinition : beanDefines) {
Object bean = sigletons.get(beanDefinition.getId());
try {
if(null != bean) {
//得到bean的属性集合(<bean id="personDao" class="com.test.dao.impl.PersonDaoImpl" />)
PropertyDescriptor[] pd = Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors();//包含class属性
for(PropertyDefinition propertyDefinition : beanDefinition.getProperties()) {//配置文件中用户定义的bean属性
for(PropertyDescriptor pDescriptor : pd) {
if(propertyDefinition.getName().equals(pDescriptor.getName())) {
Method setter = pDescriptor.getWriteMethod();//获取属性的setter方法
if(null != setter) {
Object value = null;
if(propertyDefinition.getRef() != null && !propertyDefinition.getRef().trim().equals("")) {
value = sigletons.get(propertyDefinition.getRef());
}else {
value = ConvertUtils.convert(propertyDefinition.getValues(), pDescriptor.getPropertyType());//注入基本类型的值
}
setter.setAccessible(true);//如果setter方法是private的话,invoke会报错,需要设置
setter.invoke(bean, value);//把引用对象注入到属性
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
- 构造函数(用的最多)
- 静态工厂
- 实例工厂
- singleton(默认):在spring ioc容器中一个bean定义只有一个实例对象,默认情况下会在容器启动的时候初始化,如果需要延迟初始化,需要在配置bean的时候加上lazy_init="true",这样只有在获取的时候才会初始化,对单个bean <bean id="person" class="com.test.bean.Person" lazy-init="true">,容器中所有bean都延迟加载<beans default-lazy-init="true">
- prototype:每次从容器获取新的bean对象 <bean id="person" class="com.test.bean.Person" scope="prototype">,在getBean的时候进行实例化
- set属性的方式注入bean:(可以被多个bean同时使用)
- 内部bean的方式注入(只可以被这一个bean使用)
- 使用构造器注入
- 使用Field注入(用于注解方式)
- 引入jar文件 common.annotations.jar
- 在xml添加配置如下
- 打开注解 <context:annotation-config />,这个配置隐式注册了多个对注释进行解析处理的处理器
- 使用@Autowired或@Resource注解方式进行装配。区别在于:@Autowired默认按类型装配,
package junit.test; import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.METHOD})
public @interface TydicResource {
/**
* Retention(保留)注解说明,这种类型的注解会被保留到那个阶段. 有三个值:
* 1.RetentionPolicy.SOURCE —— 这种类型的Annotations只在源代码级别保留,编译时就会被忽略
* 2.RetentionPolicy.CLASS —— 这种类型的Annotations编译时被保留,在class文件中存在,但JVM将会忽略
* 3.RetentionPolicy.RUNTIME —— 这种类型的Annotations将被JVM保留,所以他们能在运行时被JVM或其他使用反射机制的代码所读取和使用.
*
* Target(注解的作用目标)
*/
String name() default ""; }
package com.test.service.impl; import javax.annotation.Resource; import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service; import junit.test.TydicResource; import com.test.dao.PersonDao;
import com.test.service.PersonService; @Service("personService") @Scope("prototype")
public class PersonServiceImpl extends Object implements PersonService { // @TydicResource(name="xgw")<!-- 注解通过name寻找到bean注入 -->
@TydicResource
// @Resource
public PersonDao personDao; public PersonDao getPersonDao() {
return personDao;
}
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}
@Override
public void add() {
personDao.add();
}
}
查看set方法和field上是否加了注解
/**
* 通过注解方式注入bean
* 仿 注解处理器代码
*/
private void annotationInjectObject() {
for(String beanName : sigletons.keySet()) {
Object bean = sigletons.get(beanName);
if(null != bean) {
try {
PropertyDescriptor[] pd = Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors();//定义的javabean的属性集合
for(PropertyDescriptor pDescriptor : pd) {
Method setter = pDescriptor.getWriteMethod(); //属性的set方法
if(null != setter && setter.isAnnotationPresent(TydicResource.class)) {
TydicResource resource = setter.getAnnotation(TydicResource.class);//是否存在这个注解
Object value = null;
if(resource.name()!=null && !"".equals(resource.name())) {//注解中标明name属性
value = sigletons.get(resource.name());
}else {
value = sigletons.get(pDescriptor.getName());
if(value == null) { //如果在属性中也没有找到,就按类型去寻找
for(String key : sigletons.keySet()) {
/**
* isAssignableFrom
* either the same as, or is a superclass or * superinterface of, the class or interface
* 这个属性的类型如果是该磊的接口或者父类或者就是该类的话,返回true
*/
if(pDescriptor.getPropertyType().isAssignableFrom(sigletons.get(key).getClass())) {
value = sigletons.get(key);
break;
}
}
}
}
setter.setAccessible(true);
setter.invoke(bean, value);
}
} Field[] fields = bean.getClass().getFields();
for(Field field : fields) {
TydicResource resource = field.getAnnotation(TydicResource.class);//是否存在这个注解
Object value = null;
if(resource.name()!=null && !"".equals(resource.name())) {//注解中标明name属性
value = sigletons.get(resource.name());
}else {
value = sigletons.get(field.getName());
if(value == null) { //如果在属性中也没有找到,就按类型去寻找
for(String key : sigletons.keySet()) {
if(field.getType().isAssignableFrom(sigletons.get(key).getClass())) {
value = sigletons.get(key);
break;
}
}
}
}
field.setAccessible(true);
field.set(bean, value);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}



package com.test.aop; import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy; import com.test.service.impl.PersonServiceImpl; public class JDKProxyFactory implements InvocationHandler {
private Object targetObject; public Object createProxyInstance(Object targetObject) {
this.targetObject = targetObject;
return Proxy.newProxyInstance(targetObject.getClass().getClassLoader(),targetObject.getClass().getInterfaces(),this);
} @Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
PersonServiceImpl personServiceImpl = (PersonServiceImpl) this.targetObject;
Object result = null;
if(personServiceImpl.getUser()!=null) {
result = method.invoke(targetObject, args);
} return result;
}
}
package com.test.aop; import java.lang.reflect.Method; import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy; import com.test.service.impl.PersonServiceImpl; public class CglibProxyFactory implements MethodInterceptor {
private Object targetObject;//代理的目标对象 public Object createProxyInstance(Object targetObject) {
this.targetObject = targetObject;
Enhancer enhancer = new Enhancer();//该类用于生成代理
/**
* cglib创建的代理,是目标对象的子类,能够复制非final修饰的所有方法
*/
enhancer.setSuperclass(this.targetObject.getClass());//设置父类
enhancer.setCallback(this);//设置回调用对象本身
return enhancer.create();
} @Override
public Object intercept(Object proxy, Method method, Object[] aobj,
MethodProxy methodproxy) throws Throwable {
PersonServiceImpl personServiceImpl = new PersonServiceImpl();
Object result = null;
if(personServiceImpl.getUser() != null) {
result = methodproxy.invoke(targetObject, aobj);
}
return result;
} }
- 引入命名空间

- 直接配置在spring的配置文件中
- 配置在配置文件(db.properties)中




Spring框架的初步学习的更多相关文章
- Spring框架-AOP详细学习[转载]
参考博客:https://blog.csdn.net/qq_22583741/article/details/79589910#4-%E4%BE%9D%E8%B5%96%E6%B3%A8%E5%85% ...
- Spring框架零基础学习(一):IOC|DI、AOP
文章目录 一.IDEA创建Spring项目 二.Spring: IOC和DI 三.Spring: AOP 参考链接: HOW2J.CN:Spring idea创建一个spring项目 一.IDEA创建 ...
- 学习Spring框架等技术的方向、方法和动机
学习Spring框架最早学习Spring框架是在大二的时候,当时看了几本书,看了一些视频,主要是传智播客的.更多的,还是写代码,单独写Spring的,也有与Struts和Hibernate等框架整合的 ...
- 一文深入浅出学习Spring框架系列,强烈推荐
本系列主要介绍Spring框架整体架构,Spring的核心IOC,AOP的案例和具体实现机制:以及SpringMVC框架的案例和实现机制.@pdai 相关文章 首先, 从Spring框架的整体架构和组 ...
- Spring框架学习一
Spring框架学习,转自http://blog.csdn.net/lishuangzhe7047/article/details/20740209 Spring框架学习(一) 1.什么是Spring ...
- 老周的ABP框架系列教程 -》 一、框架理论初步学习
老周的ABP框架系列教程 -- 一.框架理论初步学习 1. ABP框架的来源与作用简介 1.1 简介 1.1.1 ABP框架全称为"ASP.NET Boilerplate ...
- Spring框架学习之第2节
传统的方法和使用spring的方法 使用spring,没有new对象,我们把创建对象的任务交给了spring的框架,通过配置用时get一下就行. 项目结构 applicationContext.xml ...
- Spring框架学习 - 配置
[资料] ★★☆ Spring 中提供一些Aware相关接口,像是BeanFactoryAware. ApplicationContextAware.ResourceLoaderAware.Servl ...
- 深入浅出学习Spring框架(四):IoC和AOP的应用——事务配置
在前文 深入浅出学习Spring框架(一):通过Demo阐述IoC和DI的优势所在. 深入浅出学习Spring框架(三):AOP 详解 分别介绍了Spring的核心功能——IoC和AOP,光讲知识远远 ...
随机推荐
- 记RedisDesktopManager的一次崩溃
redis3.2的配置文件中有bind监听地址 bind 192.168.42.131默认bind的填写的127.0.0.1这样配置是只允许本地访问,如果想远程访问就改为本机网卡绑定的ip地址.我这边 ...
- RSA加密解密操作
国内私募机构九鼎控股打造APP,来就送 20元现金领取地址:http://jdb.jiudingcapital.com/phone.html内部邀请码:C8E245J (不写邀请码,没有现金送)国内私 ...
- 计算内存容量(measure)
$m =gwmi Win32_PhysicalMemory $m|measure -Property capacity #计算 Property 出现次数 $m|measure -Property c ...
- ASM集群文件系统ACFS(ASM Cluster File System)
在11g R2中ASM文件支持包括数据文件,控制文件,归档日志文件,spfile,RMAN备份文件,Change Tracking文件,数据泵Dump文件盒OCR文件等.而推出的ACFS和Oracle ...
- 导出项目为jar包
- android110 jni01
##交叉编译(编译就是编译成汇编指令,使得电脑能够识别,比如windows平台模拟linux平台编译出来得程序可以在linux上运行.) * 在一个平台下,编译出另一个平台能够执行的二进制的代码 * ...
- last_9t's_ramsey
cannot finish his face
- ognl表达式和s标签
1.ognl表达式: Ognl上下文对象:(他是一个可以存储数据的空间结构,而且在这个结构中包含之前 jsp中的作用域对象) (放在 value stack控件),当前访问的Action这个上下文对象 ...
- ruby gem源更换国内源gems.ruby-china.org数据源
gem sources -l gem sources --add https://gems.ruby-china.org/ --remove https://rubygems.org/ 更新缓存 ge ...
- ZooKeeper 分布式锁实现
1 场景描述 在分布式应用, 往往存在多个进程提供同一服务. 这些进程有可能在相同的机器上, 也有可能分布在不同的机器上. 如果这些进程共享了一些资源, 可能就需要分布式锁来锁定对这些资源的访问. 2 ...