配置文件beans2.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- 把针对注解的容器注射到Spring容器中 -->
<context:annotation-config />
<bean id="personDaoxx" class="test.spring.dao.impl.PersonDaoBean" />
<!-- <bean id="personService" class="test.spring.service.impl.PersonServiceBean4"></bean> -->
<bean id="personService" class="test.spring.service.impl.PersonServiceBean3"></bean>
</beans>
package test.spring.dao;

public interface PersonDao {

    public abstract void add();

}
package test.spring.dao.impl;

import test.spring.dao.PersonDao;

public class PersonDaoBean implements PersonDao {

    @Override
public void add(){
System.out.println("执行PersonDaoBean里的test1()方法");
}
}
package test.spring.service;

public interface PersonService2 {

    public abstract void save();
}
package test.spring.service.impl;

import test.spring.dao.PersonDao;
import test.spring.jnit.AnnotationTest;
import test.spring.service.PersonService2; public class PersonServiceBean3 implements PersonService2 { private PersonDao personDao;
private String name; public PersonServiceBean3() { } public PersonServiceBean3(PersonDao personDao, String name) {
this.personDao = personDao;
this.name = name;
} public PersonDao getPersonDao() {
return personDao;
} @AnnotationTest
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} @Override
public void save() {
// TODO Auto-generated method stub
personDao.add();
// System.out.println(name);
}
}
package test.spring.jnit;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; import org.dom4j.Element; //选择在执行期
@Retention(RetentionPolicy.RUNTIME)
// 指定注解仅仅能用在字段和方法上
@Target({ ElementType.FIELD, ElementType.METHOD })
public @interface AnnotationTest { public String name() default "";
}
package test.spring.jnit;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.apache.commons.beanutils.ConvertUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader; import test.spring.entity.Bean2;
import test.spring.entity.Property; public class AnnotationInjectTest { private List<Bean2> beanDefines = new ArrayList<Bean2>();
private Map<String, Object> singletons = new HashMap<String, Object>(); public AnnotationInjectTest(String filename) {
this.readXML(filename);
this.instanceBeans();
this.injectObject();
this.annotationInject();
} private void annotationInject() {
// TODO Auto-generated method stub
for (String beanName : singletons.keySet()) {
Object bean = singletons.get(beanName);
if (bean != null) {
try {
PropertyDescriptor[] pDescriptors = Introspector
.getBeanInfo(bean.getClass())
.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : pDescriptors) {
Method setter = propertyDescriptor
.getWriteMethod();
if (setter != null
&& setter
.isAnnotationPresent(AnnotationTest.class)) {
AnnotationTest aTest = setter
.getAnnotation(AnnotationTest.class);
Object value = null;
if (aTest.name() != null
&& !"".equals(aTest.name())) {
value = singletons.get(aTest.name());
setter.setAccessible(true);
try {
setter.invoke(bean, value);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
value = singletons.get(propertyDescriptor
.getName());
if (value == null) {
for (String key : singletons.keySet()) {
if (propertyDescriptor
.getPropertyType()
.isAssignableFrom(
singletons.get(key)
.getClass())) {
value = singletons.get(key);
break;
}
}
}
}
setter.setAccessible(true);
try {
setter.invoke(bean, value);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Field[] fields = bean.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(AnnotationTest.class)) {
AnnotationTest aTest = field
.getAnnotation(AnnotationTest.class);
Object value = null;
if (aTest.name() != null
&& !"".equals(aTest.name())) {
value = singletons.get(aTest.name()); } else {
value = singletons.get(field.getName());
if (value == null) {
for (String key : singletons.keySet()) {
if (field.getType().isAssignableFrom(
singletons.get(key).getClass())) {
value = singletons.get(key);
break;
}
}
}
}
field.setAccessible(true);
try {
field.set(bean, value);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} catch (IntrospectionException e) {
e.printStackTrace();
}
}
}
} /**
* 为bean对象的属性注入值
*/
private void injectObject() {
for (Bean2 beanDefinition : beanDefines) {
Object bean = singletons.get(beanDefinition.getId());
if (bean != null) {
try {
PropertyDescriptor[] ps = Introspector.getBeanInfo(
bean.getClass()).getPropertyDescriptors();
for (Property propertyDefinition : beanDefinition
.getProperties()) {
for (PropertyDescriptor properdesc : ps) {
if (propertyDefinition.getName().equals(
properdesc.getName())) {
java.lang.reflect.Method setter = properdesc
.getWriteMethod();// 获取属性的setter方法
// ,private
if (setter != null) {
Object value = null;
if (propertyDefinition.getRef() != null
&& !"".equals(propertyDefinition
.getRef().trim())) {
value = singletons
.get(propertyDefinition
.getRef());
} else {
value = ConvertUtils.convert(
propertyDefinition.getValue(),
properdesc.getPropertyType());
}
setter.setAccessible(true);
setter.invoke(bean, value);// 把引用对象注入到属性
}
break;
}
}
}
} catch (Exception e) {
}
}
}
} /**
* 完毕bean的实例化
*/
private void instanceBeans() {
for (Bean2 beanDefinition : beanDefines) {
try {
if (beanDefinition.getClassPath() != null
&& !"".equals(beanDefinition.getClassPath().trim()))
singletons.put(beanDefinition.getId(),
Class.forName(beanDefinition.getClassPath())
.newInstance());
} catch (Exception e) {
e.printStackTrace();
}
} } /**
* 读取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属性值
Bean2 beanDefine = new Bean2(id, clazz);
XPath propertysub = element.createXPath("ns:property");
propertysub.setNamespaceURIs(nsMap);// 设置命名空间
List<Element> propertys = propertysub.selectNodes(element);
for (Element property : propertys) {
String propertyName = property.attributeValue("name");
String propertyref = property.attributeValue("ref");
String propertyValue = property.attributeValue("value");
Property propertyDefinition = new Property(propertyName,
propertyref, propertyValue);
beanDefine.getProperties().add(propertyDefinition);
}
beanDefines.add(beanDefine);
}
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 获取bean实例
*
* @param beanName
* @return
*/
public Object getBean(String beanName) {
return this.singletons.get(beanName);
} }
package test.spring.jnit;

import org.junit.Test;
import test.spring.service.PersonService2; public class SpringTest4 { @Test
public void testAnnotationInject() {
AnnotationInjectTest applicationContext = new AnnotationInjectTest(
"beans2.xml");
PersonService2 personService = (PersonService2) applicationContext
.getBean("personService");
personService.save();
} }

待续

Spring(八)编码剖析@Resource注解的实现原理的更多相关文章

  1. (转)编码剖析@Resource注解的实现原理

    http://blog.csdn.net/yerenyuan_pku/article/details/52860046 上文我们已经学会使用@Resource注解注入属性.学是学会了,但也仅限于会使用 ...

  2. Spring2.5学习3.2_编码剖析@Resource注解的实现原理

    首先看一下J2EE提供的@Resource注解:该注解默认安照名称进行装配,名称能够通过name属性进行指定, 假设没有指定name属性,当注解写在字段上时,默认取字段名进行依照名称查找,假设注解写在 ...

  3. Spring、编码剖析Spring管理Bean的原理

    引入dom4j jar包 1.新建Person接口和PersonBean public interface PersonIService { public void helloSpring(); } ...

  4. Spring源码剖析7:AOP实现原理详解

    前言 前面写了六篇文章详细地分析了Spring Bean加载流程,这部分完了之后就要进入一个比较困难的部分了,就是AOP的实现原理分析.为了探究AOP实现原理,首先定义几个类,一个Dao接口: pub ...

  5. Spring第七弹—依赖注入之注解方式注入及编码解析@Resource原理

        注入依赖对象可以采用手工装配或自动装配,在实际应用中建议使用手工装配,因为自动装配会产生未知情况,开发人员无法预见最终的装配结果. 手工装配依赖对象  手工装配依赖对象,在这种方式中又有两种编 ...

  6. 编码实现Spring 利用@Resource注解实现bean的注入,xml实现基本数据类型的注入

    首先分析. 1: 肯定要利用dom4j读取xml配置文件,将所有的bean的配置信息读取出来 2: 利用反射技术,实例化所有的bean 3: 写注解处理器, 利用注解和内省实现依赖对象的注入. 4: ...

  7. Spring中@Autowired注解、@Resource注解的区别

    Spring不但支持自己定义的@Autowired注解,还支持几个由JSR-250规范定义的注解,它们分别是@Resource.@PostConstruct以及@PreDestroy. @Resour ...

  8. 转:Spring中@Autowired注解、@Resource注解的区别

    Pay attention: When using these annotations, the object itself has to be created by Spring context. ...

  9. Spring中 @Autowired注解与@Resource注解的区别

    Spring中 @Autowired注解与@Resource注解的区别在Spring 3.X中经常使用到@Autowired和@Resource进行装配.这两个注解的差异在何处???相同点:@Reso ...

随机推荐

  1. SuSE Linux10.1 网络设置以及和主机通信end

    设置步骤如下: 1.首先判断VMware Bridge Protocol协议是否已经安装.在本地连接的属性中可以查看. 2.虚拟机设置为bridged 3. 虚拟机-Edit-Virtual Netw ...

  2. 移动开发之css3实现背景渐变效果

    前段时间由于手机项目需要实现一个背景渐变功能,  开始是想切个小背景图平铺下,  后来想到css3可以实现,如是用下面的代码就实现了. .sec_case_list li  span{ backgro ...

  3. 【SQL】宿主语言接口

    一般情况下,SQL语句是嵌套在宿主语言(如C语言)中的.有两种嵌套方式: 1.调用层接口(CLI):提供一些库,库中的函数和方法实现SQL的调用 2.直接嵌套SQL:在代码中嵌套SQL语句,提交给预处 ...

  4. 【C++】复制构造函数

    参考资料:黄邦勇帅(里面对于临时变量的说法我不是很理解,感觉里面的解释有问题) 用到复制构造函数的情况: 1.函数值传递 2.返回对象 3.用一个对象初始化另一个对象 重点注意下面两种情况: ① 只调 ...

  5. selenium 多表单切换处理(iframe/frame)

    在web应用中,前台网页的设计一般会用到iframe/frame表单嵌套页面的应用.简单的就是一个页面签嵌套多个HEML/JSP文件.selenium webdriver  只能在同一页面识别定位元素 ...

  6. python-函数(命名空间、作用域、闭包)

    一.命名空间 全局命名空间 局部命名空间 内置命名空间 *内置命名空间中存放了python解释器为我们提供的名字:input,print,str,list,tuple...它们都是我们熟悉的,拿过来就 ...

  7. pipreqs------查找python项目依赖并生成requirements.txt

    项目开发的时候,总是要搭建和部署环境,这时,就需要一个python第三方包的list,一般叫做requirements.txt.如果项目使用virtualenv环境,直接使用pip freeze即可, ...

  8. Gitlab,这也就O了???

    最简单配置也是一句话搞了... rpm -i gitlab-ce--ce..el7.x86_64.rpm vim /etc/gitlab/gitlab.rb gitlab-ctl reconfigur ...

  9. 最适合2018年自学的web前端零基础系统学习视频+资料

    这份资料整理花了近7天,如果感觉有用,可以分享给更有需要的人. 在看接下的介绍前,我先说一下整理这份资料的初衷: 我的初衷是想帮助在这个行业发展的朋友和童鞋们,在论坛博客等地方少花些时间找资料,把有限 ...

  10. NYOJ 6.喷水装置(一)-贪心

    喷水装置(一) 时间限制:3000 ms  |  内存限制:65535 KB 难度:3   描述 现有一块草坪,长为20米,宽为2米,要在横中心线上放置半径为Ri的喷水装置,每个喷水装置的效果都会让以 ...