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,光讲知识远远 ...
随机推荐
- Kooboo中主要的几个关键词中的关系
Kooboo中主要的几个关键词中的关系 Content Type //相当于数据库表 Content //相当于数据 View //部分View 她可以使用Content ...
- linux下查询域名或IP注册信息的操作记录(whois)
在运维工作中,有时需要查询某些域名的注册信息(域名的NS,注册用户,注册邮箱等),可以使用whois这个命令.whois命令令用来查找并显示指定帐号(或域名)的用户相关信息,因为它是到Network ...
- spring + springmvc + jdbc + quartz + maven整合
个人搭建框架: pom.xml: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="htt ...
- eclipse 插件之Code Folding
功能: eclipse自带折叠包括方法, import, 注释等得折叠功能, code folding 插件对其增强. 1. 下载插件:( 也可以用link方式, 我的是link安装, jar包网上很 ...
- OOP设计模式[JAVA]——02观察者模式
观察者模式 观察者模式的设计原则 为交互对象之间的松耦合设计而努力,使对象之间的相互依赖降到最低. 观察者模式也是对象行为型模式,其意图为:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时 ...
- 读取xml格式文件
$v = [xml]get-content d:\vmconfig.xml $v.Domain.Computer.Name =========================== $v.GetElem ...
- Microsoft.Net中数字签名技术
概 述:本文以Microsoft.Net中创建签名的CAB文件为例,说明如何创建签名文件,从而使你的代码能够安全的在INTERNET上公布.希望能起到抛转引玉的作用. keyword:数字签名,Act ...
- 利用PS脚本自动删除7天之前建立的目录-方法1!
目前有一个备份目录,目录名称为d:\temp\bak目录,在这目录下,根据备份要求,自动生成了如下目录的列表: 20131012 20131011 20131010 20131009 20131008 ...
- 用Python和FFmpeg查找大码率的视频文件
用Python和FFmpeg查找大码率的视频文件 本文使用Python2.7, 这个工作分两步 遍历目录下的视频文件 用ffprobe获取是视频文件的码率信息 用ffprobe 获取json格式的视频 ...
- iOS多线程开发--NSThread NSOperation GCD
多线程 当用户播放音频.下载资源.进行图像处理时往往希望做这些事情的时候其他操作不会被中 断或者希望这些操作过程中更加顺畅.在单线程中一个线程只能做一件事情,一件事情处理不完另一件事就不能开始,这样势 ...