我试图理解我是否可以将反射与弹簧依赖注入相结合,如下所示:
public interface ClientCommand {
public void execute(...);
public static enum Command {
SomeCommand(SomeCommand.class);
private Class extends ClientCommand> clazz;
private Command(Class extends ClientCommand> clazz) {
this.clazz = clazz;
}
public Class extends ClientCommand> getClazz() {
return clazz;
}
public static ClientCommand getClientCommand(String name) {
Command command = Enum.valueOf(Command.class,name);
return command.getClazz().newInstance();
}
}
}
这将基于getClientCommand中传递的名称创建命令类的实例.
这是扩展ClientCommand的类的示例:
public class LoginCommand implements ClientCommand {
@Autowired
private UserRepository userRepository;
public void setUserRepository(@Qualifier("userRepository")UserRepository userRepository) {
this.userRepository = userRepository;
}
public void execute(...) {
...
}
}
存储库是这样的:
@Repository("userRepository")
public class UserRepositoryImpl implements UserRepository {
....
}
执行LoginCommand.execute()方法时,UserRepository为null.
如果我使用newInstance()来创建对象,那么Spring会注意注入依赖项吗?
不仅仅是实际应用,还要了解理论上是否有可能使这段代码正常工作.
提前致谢
最佳答案
要回答这个问题:
If I use the newInstance() to create the object,does spring care at all to inject the dependencies?
我会回答不,不是默认. Spring只会对Spring控制的对象注入依赖关系,如果你使用反射来实例化它,或者是new运算符,那么你就是控制者,而不是Spring.
但是,有希望.使用new运算符时,甚至在使用Class.newInstance()时,可以使用AspectJ进行字节码编织.
有关此方法的更多信息,请查看此Spring documentation.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。