反射的简单使用
class Student{
private Score score;
@Resource
private HandlerService handler;
private Student(Score score) {
this.score = score;
}
}
Score score = new Score;
Class class = Student.class;
Constructor constructor = class.getConstructor(Score.class);
Student s = constructor.newInstance(score);
内部调用其他服务问题
问题说明
开发中我们通常会使用Spring框架的注解来直接获取类的实例,因此在使用反射的时候就会习惯性还是用注解,如上面代码所示,这会导致handler为null。因为利用反射构造类的时候没有通过spring,那么该实例中的注解也不会生效。
问题解决
这种情况下,方法之一是将内部服务在构造函数中初始化以便获取实例。
class Student{
private Score score;
@Resource
private HandlerService handler;
private Student(Score score, ApplicationContext applicationContext) {
this.score = score;
this.handler = applicationContext.getBean(HandlerService.class);
}
}
Class Main implements ApplicationContextAware {
private ApplicationContext applicationContext;
Score score = new Score;
public void test() {
Class class = Student.class;
Constructor constructor = class.getConstructor(Score.class, ApplicationContext.class);
Student s = constructor.newInstance(score,applicationContext);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
网友评论