spring注入机制核心原理

其实spring是基于java的反射机制,现在举个示例看一下:

比如有个User类


public class User {
   String userName;
   String password;
/**
* @return the userName
*/
public String getUserName() {
   return userName;
}
/**
* @param userName the userName to set
*/
public void setUserName(String userName) {
   this.userName = userName;
}
/**
* @return the password
*/
public String getPassword() {
   return password;
}
/**
* @param password the password to set
*/
public void setPassword(String password) {
   this.password = password;
}
/*
* 打印用户信息
*/
public void printInfo(){
   System.out.println("userName:"+userName+",password:"+password);

}
}

然后我们再写一个类对其进行反射

import java.lang.reflect.Method;


public class Reflect {
public static void main(String[] args) {
   try{
    //根据类名(spring中是从applicationContext.xml中读取的)获得其类,注意这时还不是实例,只是个类
    Class<?> objClass=Class.forName("User");
    /*
    * 由类获取setter方法(spring中是从applicationContext.xml中读取的)
    * 第一个参数据是方法名,第二个是方法的参数(这里这用的是String类),可以是数组表示多个参数
    */
    Method setNameMethod=objClass.getMethod("setUserName", String.class);
    Method setPasswordMethod=objClass.getMethod("setPassword", String.class);
    //有的方法是private,设置方法的访问属性为可访问
    setNameMethod.setAccessible(true);
    setPasswordMethod.setAccessible(true);
    //实例化对象
    Object obj=objClass.newInstance();
    //调用方法进行注入
    setNameMethod.invoke(obj, new String("shirui"));
    setPasswordMethod.invoke(obj, new String("0000"));
    //此时完成注入,我们进行测一下
    User user=(User)obj;//spring中是ctx.getBean("user");
    user.printInfo();
    /*
    * 到此完成spring底层的反射机制
    */
   }catch(Exception e){
    e.printStackTrace();
   }
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值