框架部分
public abstract class ApplicationContext {
public abstract Object getBean(String id);
}
public class BeanDefinetion {
private String id;
private String type;
private List<PropertyDefinition> propertyDefinitions=new ArrayList<PropertyDefinition>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<PropertyDefinition> getPropertyDefinitions() {
return propertyDefinitions;
}
public void setPropertyDefinitions(List<PropertyDefinition> propertyDefinitions) {
this.propertyDefinitions = propertyDefinitions;
}
public BeanDefinetion(String id, String type) {
this.id = id;
this.type = type;
}
}
public class PropertyDefinition {
private String name;
private String ref;
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRef() {
return ref;
}
public void setRef(String ref) {
this.ref = ref;
}
public PropertyDefinition(String name, String ref,String value) {
this.name = name;
this.ref = ref;
this.value=value;
}
}
属性或字段注入注解
@Target({ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface YmResource {
public String name() default "";
}
对象注解
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface YmService {
String value() default "";
}
容器实现
package spring;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Administrator
*/
public class ClassPathXmlApplicationContext extends ApplicationContext {
private Map<String, Object> singletons = new HashMap<String, Object>();
private List<BeanDefinetion> beanDefinetions = new LinkedList<BeanDefinetion>();
private List<String> beansFile = new LinkedList<String>();
private InputStream input;
private String basepcakage;
public ClassPathXmlApplicationContext(String file) {
try {
input = getClass().getResourceAsStream(file);
parseXML();//xml解析
beanInstance();//基于xml的对象实例
beanAnnotationInstance();//基于注解的对象实例
injectObject();//基于xml的对象注入
injectAnnotationObject();//基于注解的对象注入
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void beanAnnotationInstance() throws Exception {
System.out.println(beanDefinetions);
for (BeanDefinetion beanDefinetion : beanDefinetions) {
Class z = Class.forName(beanDefinetion.getType());
singletons.put(beanDefinetion.getId(), z.newInstance());
}
System.out.println(singletons);
}
public void list(File file) throws Exception {
String id = null;
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
list(f);
}
} else {
if (file.getName().endsWith(".class")) {
// System.out.println(file.getName().replace(".class", ""));
String type = getType(file);
Class z = Class.forName(type);
if (z.isAnnotationPresent(YmService.class)) {
Annotation[] annotations = z.getAnnotations();
for (Annotation annotation : annotations) {
if (annotation.annotationType() == YmService.class) {
id = ((YmService) annotation).value();
}
}
BeanDefinetion beanDefinetion = new BeanDefinetion(id, type);
beanDefinetions.add(beanDefinetion);
}
}
}
}
private String getType(File file) {
String path = file.getPath();
path = path.substring(path.indexOf("classes")).replace("classes" + File.separator, "");
return path.replace(File.separator, ".").replace(".class", "");
}
private void injectAnnotationObject() throws Exception {
for (BeanDefinetion beanDefinetion : beanDefinetions) {
PropertyDescriptor[] propertyDescriptors = java.beans.Introspector.getBeanInfo(Class.forName(beanDefinetion.getType())).getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
Method setter = propertyDescriptor.getWriteMethod();
if (setter != null && setter.isAnnotationPresent(YmResource.class)) {
YmResource ymResource = setter.getAnnotation(YmResource.class);
String ref = ymResource.name();
setter.setAccessible(true);
setter.invoke(singletons.get(beanDefinetion.getId()), singletons.get(ref));
}
}
Field[] fields = Class.forName(beanDefinetion.getType()).getDeclaredFields();
for (Field field : fields) {
if (field != null && field.isAnnotationPresent(YmResource.class)) {
YmResource ymResource = field.getAnnotation(YmResource.class);
String ref = ymResource.name();
field.setAccessible(true);
field.set(singletons.get(beanDefinetion.getId()), singletons.get(ref));
}
}
}
}
private void injectObject() throws Exception {
for (BeanDefinetion beanDefinetion : beanDefinetions) {
for (PropertyDefinition propertyDefinition : beanDefinetion.getPropertyDefinitions()) {
PropertyDescriptor[] propertyDescriptors = java.beans.Introspector.getBeanInfo(Class.forName(beanDefinetion.getType())).getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
if (propertyDescriptor.getName().equals(propertyDefinition.getName())) {
Method setter = propertyDescriptor.getWriteMethod();
setter.setAccessible(true);
if (propertyDefinition.getValue() == null) {
setter.invoke(singletons.get(beanDefinetion.getId()), singletons.get(propertyDefinition.getName()));
} else {
setter.invoke(singletons.get(beanDefinetion.getId()), propertyDefinition.getValue());
}
}
}
}
}
}
private void parseXML() throws Exception {
SAXReader reader = new SAXReader();
Document doc = reader.read(input);
Map<String, String> ns = new HashMap<String, String>();
ns.put("ns", "http://www.springframework.org/schema/beans");
XPath xpath = doc.createXPath("//ns:beans/ns:bean");
xpath.setNamespaceURIs(ns);
List<Element> elements = xpath.selectNodes(doc);
for (Element element : elements) {
String id = element.attributeValue("id");
String type = element.attributeValue("class");
BeanDefinetion beanDefinetion = new BeanDefinetion(id, type);
beanDefinetions.add(beanDefinetion);
List<Element> propertys = element.selectNodes("property");
for (Element property : propertys) {
String name = property.attributeValue("name");
String ref = property.attributeValue("ref");
String value = property.attributeValue("value");
PropertyDefinition propertyDefinition = new PropertyDefinition(name, ref, value);
beanDefinetion.getPropertyDefinitions().add(propertyDefinition);
}
}
ns = new HashMap<String, String>();
ns.put("context", "http://www.springframework.org/schema/context");
xpath = doc.createXPath("//context:component-scan");
xpath.setNamespaceURIs(ns);
elements = xpath.selectNodes(doc);
System.out.println(elements);
Element element = elements.get(0);
basepcakage = element.attributeValue("base-package");
System.out.println(basepcakage);
try {
Enumeration enumer = ClassLoader.getSystemResources(basepcakage);
while (enumer.hasMoreElements()) {
URL path = (URL) enumer.nextElement();
list(new File(path.getFile()));
}
} catch (IOException ex) {
Logger.getLogger(ClassPathXmlApplicationContext.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void beanInstance() throws Exception {
for (BeanDefinetion beanDefinetion : beanDefinetions) {
Object o = Class.forName(beanDefinetion.getType()).newInstance();
singletons.put(beanDefinetion.getId(), o);
}
}
@Override
public Object getBean(String id) {
return singletons.get(id);
}
}
测试的部分
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context">
<context:component-scan base-package="ym"/>
<bean id="test" class="ym.Test"/>
</beans>
public interface ProductDao {
public void insert();
}
@YmService("productDao")
public class ProductDaoBean implements ProductDao{
public void insert() {
System.out.println("svae............");
}
}
public interface ProductService {
void newProduct();
}
@YmService("productService")
public class ProductServiceBean implements ProductService{
public void newProduct() {
productDao.insert();
System.out.print(name);
}
@YmResource(name="productDao") private ProductDao productDao;
public ProductDao getProductDao() {
return productDao;
}
// @YmResource(name="productDao")
public void setProductDao(ProductDao productDao) {
this.productDao = productDao;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Test {
public static void main(String[] args) {
//ProductService productService=new ProductServiceBean();
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
ProductService productService=(ProductService)ctx.getBean("productService");
productService.newProduct();
}
}
public abstract class ApplicationContext {
public abstract Object getBean(String id);
}
public class BeanDefinetion {
private String id;
private String type;
private List<PropertyDefinition> propertyDefinitions=new ArrayList<PropertyDefinition>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<PropertyDefinition> getPropertyDefinitions() {
return propertyDefinitions;
}
public void setPropertyDefinitions(List<PropertyDefinition> propertyDefinitions) {
this.propertyDefinitions = propertyDefinitions;
}
public BeanDefinetion(String id, String type) {
this.id = id;
this.type = type;
}
}
public class PropertyDefinition {
private String name;
private String ref;
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRef() {
return ref;
}
public void setRef(String ref) {
this.ref = ref;
}
public PropertyDefinition(String name, String ref,String value) {
this.name = name;
this.ref = ref;
this.value=value;
}
}
属性或字段注入注解
@Target({ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface YmResource {
public String name() default "";
}
对象注解
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface YmService {
String value() default "";
}
容器实现
package spring;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Administrator
*/
public class ClassPathXmlApplicationContext extends ApplicationContext {
private Map<String, Object> singletons = new HashMap<String, Object>();
private List<BeanDefinetion> beanDefinetions = new LinkedList<BeanDefinetion>();
private List<String> beansFile = new LinkedList<String>();
private InputStream input;
private String basepcakage;
public ClassPathXmlApplicationContext(String file) {
try {
input = getClass().getResourceAsStream(file);
parseXML();//xml解析
beanInstance();//基于xml的对象实例
beanAnnotationInstance();//基于注解的对象实例
injectObject();//基于xml的对象注入
injectAnnotationObject();//基于注解的对象注入
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void beanAnnotationInstance() throws Exception {
System.out.println(beanDefinetions);
for (BeanDefinetion beanDefinetion : beanDefinetions) {
Class z = Class.forName(beanDefinetion.getType());
singletons.put(beanDefinetion.getId(), z.newInstance());
}
System.out.println(singletons);
}
public void list(File file) throws Exception {
String id = null;
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
list(f);
}
} else {
if (file.getName().endsWith(".class")) {
// System.out.println(file.getName().replace(".class", ""));
String type = getType(file);
Class z = Class.forName(type);
if (z.isAnnotationPresent(YmService.class)) {
Annotation[] annotations = z.getAnnotations();
for (Annotation annotation : annotations) {
if (annotation.annotationType() == YmService.class) {
id = ((YmService) annotation).value();
}
}
BeanDefinetion beanDefinetion = new BeanDefinetion(id, type);
beanDefinetions.add(beanDefinetion);
}
}
}
}
private String getType(File file) {
String path = file.getPath();
path = path.substring(path.indexOf("classes")).replace("classes" + File.separator, "");
return path.replace(File.separator, ".").replace(".class", "");
}
private void injectAnnotationObject() throws Exception {
for (BeanDefinetion beanDefinetion : beanDefinetions) {
PropertyDescriptor[] propertyDescriptors = java.beans.Introspector.getBeanInfo(Class.forName(beanDefinetion.getType())).getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
Method setter = propertyDescriptor.getWriteMethod();
if (setter != null && setter.isAnnotationPresent(YmResource.class)) {
YmResource ymResource = setter.getAnnotation(YmResource.class);
String ref = ymResource.name();
setter.setAccessible(true);
setter.invoke(singletons.get(beanDefinetion.getId()), singletons.get(ref));
}
}
Field[] fields = Class.forName(beanDefinetion.getType()).getDeclaredFields();
for (Field field : fields) {
if (field != null && field.isAnnotationPresent(YmResource.class)) {
YmResource ymResource = field.getAnnotation(YmResource.class);
String ref = ymResource.name();
field.setAccessible(true);
field.set(singletons.get(beanDefinetion.getId()), singletons.get(ref));
}
}
}
}
private void injectObject() throws Exception {
for (BeanDefinetion beanDefinetion : beanDefinetions) {
for (PropertyDefinition propertyDefinition : beanDefinetion.getPropertyDefinitions()) {
PropertyDescriptor[] propertyDescriptors = java.beans.Introspector.getBeanInfo(Class.forName(beanDefinetion.getType())).getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
if (propertyDescriptor.getName().equals(propertyDefinition.getName())) {
Method setter = propertyDescriptor.getWriteMethod();
setter.setAccessible(true);
if (propertyDefinition.getValue() == null) {
setter.invoke(singletons.get(beanDefinetion.getId()), singletons.get(propertyDefinition.getName()));
} else {
setter.invoke(singletons.get(beanDefinetion.getId()), propertyDefinition.getValue());
}
}
}
}
}
}
private void parseXML() throws Exception {
SAXReader reader = new SAXReader();
Document doc = reader.read(input);
Map<String, String> ns = new HashMap<String, String>();
ns.put("ns", "http://www.springframework.org/schema/beans");
XPath xpath = doc.createXPath("//ns:beans/ns:bean");
xpath.setNamespaceURIs(ns);
List<Element> elements = xpath.selectNodes(doc);
for (Element element : elements) {
String id = element.attributeValue("id");
String type = element.attributeValue("class");
BeanDefinetion beanDefinetion = new BeanDefinetion(id, type);
beanDefinetions.add(beanDefinetion);
List<Element> propertys = element.selectNodes("property");
for (Element property : propertys) {
String name = property.attributeValue("name");
String ref = property.attributeValue("ref");
String value = property.attributeValue("value");
PropertyDefinition propertyDefinition = new PropertyDefinition(name, ref, value);
beanDefinetion.getPropertyDefinitions().add(propertyDefinition);
}
}
ns = new HashMap<String, String>();
ns.put("context", "http://www.springframework.org/schema/context");
xpath = doc.createXPath("//context:component-scan");
xpath.setNamespaceURIs(ns);
elements = xpath.selectNodes(doc);
System.out.println(elements);
Element element = elements.get(0);
basepcakage = element.attributeValue("base-package");
System.out.println(basepcakage);
try {
Enumeration enumer = ClassLoader.getSystemResources(basepcakage);
while (enumer.hasMoreElements()) {
URL path = (URL) enumer.nextElement();
list(new File(path.getFile()));
}
} catch (IOException ex) {
Logger.getLogger(ClassPathXmlApplicationContext.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void beanInstance() throws Exception {
for (BeanDefinetion beanDefinetion : beanDefinetions) {
Object o = Class.forName(beanDefinetion.getType()).newInstance();
singletons.put(beanDefinetion.getId(), o);
}
}
@Override
public Object getBean(String id) {
return singletons.get(id);
}
}
测试的部分
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context">
<context:component-scan base-package="ym"/>
<bean id="test" class="ym.Test"/>
</beans>
public interface ProductDao {
public void insert();
}
@YmService("productDao")
public class ProductDaoBean implements ProductDao{
public void insert() {
System.out.println("svae............");
}
}
public interface ProductService {
void newProduct();
}
@YmService("productService")
public class ProductServiceBean implements ProductService{
public void newProduct() {
productDao.insert();
System.out.print(name);
}
@YmResource(name="productDao") private ProductDao productDao;
public ProductDao getProductDao() {
return productDao;
}
// @YmResource(name="productDao")
public void setProductDao(ProductDao productDao) {
this.productDao = productDao;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Test {
public static void main(String[] args) {
//ProductService productService=new ProductServiceBean();
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
ProductService productService=(ProductService)ctx.getBean("productService");
productService.newProduct();
}
}
相关推荐
Spring Security 是一个功能强大的安全框架,可以为基于Java的应用程序提供认证(Authentication)、授权(Authorization)等功能,同时提供了丰富的配置选项来满足不同的应用场景需求。 #### 二、传统Web应用安全开发...
在IT领域,Spring框架是Java开发中的一个核心组件,它以其灵活性、可扩展性和模块化设计深受开发者喜爱。"于洋spring"是传智播客推出的一系列关于Spring框架的教程,旨在帮助初学者和进阶者深入理解并熟练掌握Spring...
3. Spring Web MVC框架:Spring Web MVC是Spring框架的一部分,它提供了一个模型-视图-控制器(MVC)实现用于构建Web应用程序。它与Spring框架的其他部分集成良好,并支持多种视图技术,如JSP、Velocity和Freemarker...
一、Spring框架简介 Spring是一个开源的Java平台,最初由Rod Johnson创建,并首次在2003年发布。它最初是为了解决企业应用开发的复杂性而设计的轻量级解决方案。Spring框架以其轻量级、POJO(Plain Old Java Objects...
讲课宝课堂互动系统适用于各类需要互动的场所,如课堂教学互动、大型活动互动等。
总结来说,"讲课用的小组评比工具"是一款强大的教学辅助软件,它将评分过程变得简单而高效,为教师提供了更全面、更公平的评价手段,同时也促进了学生的主动学习和团队合作。在信息化教育时代,这样的工具无疑能极大...
《赖世雄中级英语讲课笔记》是一份宝贵的英语学习资源,由知名英语教育专家赖世雄教授精心编纂。这份笔记涵盖了中级英语的学习要点,旨在帮助学习者提升英语能力,尤其是听力、阅读、写作和口语方面的技能。赖世雄...
课堂管理策略讲课提纲.pptx
程序中遇到另一个 `ORG` 指令时,新的地址开始计算。这样可以确保程序在内存中的连续性。 2. **等值指令**: `EQU` 指令用于给字符名称赋予一个数值或汇编符号,方便程序的编写、调试和修改。例如,`PA8155 EQU ...
Spring Boot 是一个由 Pivotal 团队开发的框架,旨在简化基于 Spring 的应用程序初始搭建以及开发过程。它集成了大量的常用第三方库配置,如 JDBC、MongoDB、JPA、RabbitMQ、Quartz 等,使得开发者可以快速地创建出...
单片机讲解,我们学校老师的课件,对单片机感兴趣的同学可以看看!
单片机5——课堂讲课课件的内容主要围绕MCS-51单片机的中断系统进行讲解,这一章深入探讨了中断的概念、中断源、中断优先级以及MCS-51单片机中断系统的具体实现。 中断是计算机系统中一种重要的机制,它允许计算机...
"课堂教学改革模式讲课讲稿"探讨了如何打破传统的教学模式,构建适应新时代需求的教育方式。改革的核心理念是以学生为中心,以教育教学理论和规律为基础,遵循新课程理念,旨在优化教学结构,提高教学效率,促进学生...
单片机应用系统的设计与开发是一个综合性的工程过程,涉及到硬件和软件的紧密配合。在开发过程中,首先要进行方案论证,了解用户需求,确定设计规模和总体框架,评估技术难度,并进行调研,确定初步设计方案。在此...
【如何做好模拟课堂讲课】 1. **充分准备**:了解应聘学科,把握教材重点,增强自信心,避免紧张导致表达不清或语速过快。 2. **教案撰写**:根据试讲时间限制,选择合适的内容,可以是某个知识点的深入讲解,而...
一篇优秀的考研英语作文通常包括三个主要部分:Introduction(引言)、Body(主体)和Conclusion(结论)。 1. Introduction(引言) - General description(整体描述):简要介绍文章主题。 - Details(细节)...
在这个“tcp协议简单讲课”中,我们将会深入探讨TCP协议的基本概念、工作原理以及它在实际网络通信中的应用。 TCP是一种面向连接的、可靠的、基于字节流的传输层通信协议。它在两台计算机之间建立连接后,才能进行...
例如,在教授编程、设计或者科学实验等需要展示步骤的课程时,教师可以连续截取每一个关键步骤,形成完整的操作流程图,方便学生课后复习或查阅。同时,实时截屏功能也使得在线教学更加生动,让学生如同亲临现场般地...
以上仅是Java高级学习的一小部分,实际的资料包可能涵盖这些主题的更多细节,例如深入的JVM优化、网络编程、数据库连接池、Spring框架的高级用法等。通过系统学习和实践,可以有效提升Java开发的专业水平。
【小黑课堂独家课程资料.rar】是一份专为学习计算机二级考试准备的资源包,它涵盖了计算机基础知识、操作系统、网络技术、数据库管理、程序设计语言等多个核心领域。这份压缩包旨在帮助学员系统地掌握和复习计算机二...