Atitit spring原理 反射 ioc 与注解api
目录
1.2. 使用apache 工具包 commons-beanutils-1.7.0.jar 1
// 获取通过注解注入容器的UserService
UserService userService = context.getBean(UserService.class);
private static UserService getBean(Class<UserService> class1) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
// com.google.common.reflect.Reflection.
UserService us= ConstructorUtils.invokeConstructor(class1, null);
return us;
}
目的:提升可读性 容易理解
//使用apache beanutil工具来实现反射
private static Object getBean(Class<?> class1) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//加载类,并且调用构造函数返回新建对象
return ConstructorUtils.invokeConstructor(class1, null);
}
package ref;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface 我的注解 {
String 属性();
String 属性2();
}
@我的注解(属性="111",属性2="2222")
public class UserService {
Class cls= UserService.class;
我的注解 anno1= (我的注解) cls.getAnnotation(我的注解.class);
System.out.println(anno1.属性());
System.out.println(anno1.属性2());