反射+弹簧依赖注入

Ae.*_*Ae. 5 java reflection spring

我试图理解我是否可以将反射与弹簧依赖注入相结合,如下所示:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这将基于getClientCommand中传递的名称创建命令类的实例.这是扩展ClientCommand的类的示例:

public class LoginCommand implements ClientCommand {
    @Autowired
    private UserRepository userRepository;

    public void setUserRepository(@Qualifier("userRepository")UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public void execute(...) {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

存储库是这样的:

@Repository("userRepository")
public class UserRepositoryImpl implements UserRepository {
    ....
}
Run Code Online (Sandbox Code Playgroud)

执行LoginCommand.execute()方法时,UserRepository为null.如果我使用newInstance()来创建对象,那么Spring会注意注入依赖项吗?不仅仅是实际应用,还要了解理论上是否有可能使这段代码正常工作.提前致谢

nic*_*ild 3

回答这个问题:

如果我使用 newInstance() 创建对象,spring 是否关心注入依赖项?

我会回答“否”,默认情况下不会。Spring只会注入对Spring控制的对象的依赖关系,如果您使用反射来实例化它或操作new符,那么就是控制者,而不是Spring。

但是,还有希望。new您可以在使用运算符时甚至Class.newInstance()使用使​​用 AspectJ 进行字节码编织

请查看此Spring 文档,了解有关此方法的更多信息。

  • 我宁愿添加示例而不是链接! (2认同)