定义一个Autowired接口
package com.biaodian.myface;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Autowired {
}
定义两个service
package com.biaodian.service;
public class HelloService {
}
package com.biaodian.service;
public class UserService {
}
定义一个controller
package com.biaodian.controller;
import com.biaodian.myface.Autowired;
import com.biaodian.service.HelloService;
import com.biaodian.service.UserService;
public class HelloController {
@Autowired
private HelloService helloService;
@Autowired
private UserService userService;
public HelloService getHelloService() {
return helloService;
}
public UserService getUserService() {
return userService;
}
}
在main方法赋值
import com.biaodian.controller.HelloController;
import com.biaodian.myface.Autowired;
import java.lang.reflect.Field;
public class Main {
public static void main(String[] args) throws IllegalAccessException, InstantiationException {
//先获取类的class
Class<HelloController> helloControllerClass = HelloController.class;
//根据class生产类对象
HelloController helloController = helloControllerClass.newInstance();
//获取class的属性遍历
for (Field declaredField : helloControllerClass.getDeclaredFields()) {
//判断属性上是否有Autowired注解
Autowired annotation = declaredField.getAnnotation(Autowired.class);
if (annotation!=null){
//私有属性时也可访问
declaredField.setAccessible(true);
//有,先获取该属性的class
Class<?> type = declaredField.getType();
//根据class获取类对象
Object o = type.newInstance();
//把该对象设置到helloController中
declaredField.set(helloController,o);
}
}
System.out.println(helloController.getUserService());
System.out.println(helloController.getHelloService());
}
}
输出打印结果
com.biaodian.service.UserService@511d50c0
com.biaodian.service.HelloService@60e53b93
Process finished with exit code 0