反射

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
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值