配置文件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. rhel5.5 linux系统下安装Oracle 11g

    一.配置环境变量1.我将环境变量配置写成了一个脚本,将这个脚本copy到一个新建的linux系统.(脚本是本人原创,前2篇文章里有,感兴趣的朋友可以去看看) 2.进入脚本所在的目录. 3.执行脚本,需 ...

  2. 【反演复习计划】【bzoj1011】zap-queries

    快三个月没做反演题了吧…… 感觉高一上学期学的全忘了…… 所以还得从零开始学推式子. # bzoj1011 标签(空格分隔): 未分类 --- 原题意思是求以下式子:$Ans=\sum\limits_ ...

  3. Android之Activity

    Activity总结: Activity的顶层View是DecorView,而我们在onCreate函数中通过setContentView设置的View只不过是这个DecorView的一部分罢了.De ...

  4. Guice 注入(@Inject注解)

    带有@Inject注解的类 使用 injector.getInstance初始化 http://blog.csdn.net/java_le/article/details/24851251 Googl ...

  5. synchronized 修饰static方法

    •1.依靠对象锁锁定 初始化一个对象时,自动有一个 对象锁. synchronized {普通方法}依靠对象锁工作,多线程访问synchronized方法,一旦某个进程抢得锁之后,其他的进程只有排队对 ...

  6. 使用bottle进行web开发(4):HTTPError

    from bottle import error @error(404) def error404(error): return 'Nothing here, sorry' 上述代码,是对404的定义 ...

  7. Centos 下,配置 Apache + Python + Django + postgresSQL 开发环境

    用 Python 搭建一个 Web 服务器 文章结构 一.安装  Apache.Python.django 二.安装 mod_wsgi,Apache 为 Python 提供的 wsgi 模块  三.将 ...

  8. pycurl mac 安装报错Curl is configured to use SSL,

    1.使用安装第三方插件的方式安装pycurl:pip3 install pycurl 报错提示如下: Curl is configured to use SSL, but we have not be ...

  9. 【转】SonarQube配置自定义的CheckStyle代码规则

    原文地址:https://www.jianshu.com/p/ff1d800885ce 惯例第一步肯定是SonarQube的安装与运行配置了,但这部分不在本文主题内,网上一搜一大把,这里就不讲了,大家 ...

  10. [centos6.5] 完全卸载httpd mysql php

    rpm -qa|grep mysql # 列出所有mysql相关包 rpm -e 包名 # 逐一卸载,一个方便技巧是:卸载时可以不带版本,比如 # mysqlclient10-3.23.58-4.RH ...