1. 程式人生 > >手寫註解版的SpringIoc

手寫註解版的SpringIoc

根據類上的註解來建立物件

1.@component("aa"),用getBean("aa",User.class)獲取
2.@component,將類名小寫作為物件名,用getBean(User.class)獲取
package com.tedu.annotation_spring;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Constructor;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 根據註解來建立物件
 * @author wan_ys
 *
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Component{
	String value() default "";
}

@Component
class User{
	private String name;
	private Integer age;
	public String getName() {
		return name;
	}
	public User(){
		
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "User [name=" + name + ", age=" + age + "]";
	}
	
	
}
public class AnnotationBeanFactory {
	/*
	 * 註解的使用和反射建立物件
	 */
	static Map<String, Object> map=new ConcurrentHashMap<String, Object>();
	public <T>T createInstance(Class<T> class1) {
		T object =null;
		try {
		Constructor<T> constructor = class1.getDeclaredConstructor();
		object= constructor.newInstance();
		}catch (Exception e) {
			e.printStackTrace();
		}
		//獲取註解
		Component component = class1.getDeclaredAnnotation(Component.class);
		if (component==null) {
			return null;
		}
		System.out.println(component);
		String value = component.value();
		if (value==null||"".equals(value)) {
			//首字母轉小寫作為物件名
			String simpleName = class1.getSimpleName();
			value=simpleName.substring(0,1).toLowerCase()+simpleName.substring(1);
		}
		map.put(value, object);
		
		return object;
	}
	
	public <T>T getBean(String key,Class<T> class1){
		Object object = map.get(key);
		if (object==null) {
			object=createInstance(class1);
			map.put(key, object);
		}
		return (T) object;
	}
	public <T>T getBean(Class<T> class1){
		//先根據類名小寫獲取key
		String simpleName = class1.getSimpleName();
		String key=simpleName.substring(0,1).toLowerCase()+simpleName.substring(1);
		return getBean(key, class1);
	}
}

簡單的測試:

package com.tedu.annotation_spring;

public class Test1 {
	public static void main(String[] args) {
		 AnnotationBeanFactory annotationBeanFactory=new AnnotationBeanFactory();
//		 User user = annotationBeanFactory.createInstance(User.class);
//		 user.setAge(10);
//		 user.setName("滴滴");
//		 System.out.println(user);
		 User bean = annotationBeanFactory.getBean(User.class);
		 bean.setAge(11);
		 bean.setName("螞蟻金服");
		 System.out.println(b