UserService
package com.springboot.fanshe;
/**
* Created by xp on 2020-12-09.
*/
public class UserService {
public UserService() {
System.out.println("cons----");
}
}
UserController
package com.springboot.fanshe;
/**
* Created by xp on 2020-12-09.
*/
public class UserController {
// @Autowired 通常是通过该注解进行注入
private UserService userService;
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
}
假如不使用@Autowired注解,如何实现注入
TEST
package com.springboot.fanshe;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* Created by xp on 2020-12-09.
*/
public class Test {
public static void main(String[] args) throws Exception {
UserService userService = new UserService();
UserController userController = new UserController();
System.out.println(userService); //com.springboot.fanshe.UserService@34c45dca
System.out.println(userController.getUserService()); //null
/*
完成注入功能
*/
Class clazz = userController.getClass();
//获取属性
Field serviceFiled = clazz.getDeclaredField("userService");
serviceFiled.setAccessible(true);
//获取对应set方法
String name = serviceFiled.getName();
System.out.println(name); //userService
name = name.substring(0, 1).toUpperCase() + name.substring(1, name.length());
System.out.println(name); //UserService
String methodName = "set" + name;
Method method = clazz.getMethod(methodName, UserService.class);
//调用setUserService方法
method.invoke(userController,userService);
System.out.println(userController.getUserService()); //com.springboot.fanshe.UserService@34c45dca
}
}