Atitit spring原理 反射 ioc 与注解api 目录 1. 反射的使用 1 1.1. 使用jdk原生反射api 1 1.2. 使用apache 工具包 commons-beanutil

Atitit spring原理 反射 ioc 与注解api

 

目录

1. 反射的使用 1

1.1. 使用jdk原生反射api 1

1.2. 使用apache 工具包  commons-beanutils-1.7.0.jar 1

2. 注解的使用 2

2.1. 注解定义 2

2.2. 注解设置使用 2

2.3. 注解读取 2

 

 

  1. 反射的使用

 

// 获取通过注解注入容器的UserService

UserService userService = context.getBean(UserService.class);

 

    1. 使用jdk原生反射api

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;

}

 

    1. 使用apache 工具包  commons-beanutils-1.7.0.jar

目的:提升可读性 容易理解

//使用apache beanutil工具来实现反射

private static Object getBean(Class<?> class1) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {

 

   //加载类,并且调用构造函数返回新建对象

return ConstructorUtils.invokeConstructor(class1, null);

 

 

}

  1. 注解的使用
    1. 注解定义

 

package ref;

 

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

 

@Retention(RetentionPolicy.RUNTIME)

public @interface 我的注解 {

 

String 属性();

 

String 属性2();

 

}

    1. 注解设置使用

 @我的注解(属性="111",属性2="2222")

public class UserService {

 

 

    1. 注解读取

Class cls= UserService.class;

我的注解   anno1=  (我的注解) cls.getAnnotation(我的注解.class);

System.out.println(anno1.属性());

System.out.println(anno1.属性2());

猜你喜欢

转载自blog.csdn.net/attilax/article/details/84594390