根据类上的注解来创建对象
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(bean);
}
}