包结构
配置类
实体类Car
package com.tuling.MySpring;
import org.springframework.stereotype.Component;
@MyComponent
public class Car {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Car() {
System.out.println("car加载....");
}
public Car(String name) {
this.name = name;
}
}
自定义注解
package com.tuling.MySpring;
import org.springframework.stereotype.Indexed;
import java.lang.annotation.*;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface MyComponent {
String value() default "myComponent";
}
GetBean类
package com.tuling.MySpring;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.util.Assert;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class MyGetBean {
public static Object getSingleton(String beanName, ObjectFactory<?> singletonFactory){
Object singletonObject = singletonFactory.getObject();
return singletonObject;
}
public static Object getBean(String beanName){
Object bean=getSingleton(beanName, () -> {
//进入创建bean的逻辑
return createBean(beanName);
});
return bean;
}
public static Object createBean(String beanName){
Properties properties=new Properties();
ClassLoader classLoader = MyGetBean.class.getClassLoader();
InputStream is = classLoader.getResourceAsStream("pro.properties");
try {
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
String className = properties.getProperty("className");
//通过反射实例化bean
//根据类名找到注解
try {
Class<?> clazz = Class.forName(MyGetBean.class.getPackage().getName()+"." + className);
MyComponent annotation = clazz.getAnnotation(MyComponent.class);
if(null!=annotation&&"myComponent".equals(annotation.value())){
Object o = clazz.newInstance();
return o;
}else{
Assert.notNull(annotation,"不是MyComponent注解的不能实例化");
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
Car car = (Car) getBean("car");
car.setName("奔驰");
System.out.println(car.getName());
}
}
运行:
结果
实例化加了自定义注解的类,只有加了@MyComponent注解的才能实例化,以后会一步一步进行扩展,未完待续