有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在动作合成中使用字段注入?

Play 2.4支持开箱即用的依赖注入控制器。我已经成功地使用构造函数注入为我的控制器提供依赖项。但是,当使用action composition时,不会注入标有@Inject的字段

有没有办法将依赖项注入到复合操作中

控制器的示例代码:

public class Application extends Controller {
    private DomainService ds;

    @Inject
    public Application(DomainService ds) {
        this.ds = ds;
    }

    @Security.Authenticated(RandomAuthenticator.class)
    public Result index() {
        return ok();
    }

}

复合操作的示例代码:

public class RandomAuthenticator extends Security.Authenticator {
    @Inject private RandomService rs; // This field is never injected

    @Override
    public String getUsername(Context context) {
        float randFloat = rs.nextFloat(); // Error! rs is always null

        if (randFloat > 0.1) {
            return "foo";
        }

        return null;
    }
}

共 (2) 个答案

  1. # 1 楼答案

    您可以尝试使用类的构造函数使用Guice进行注入,而不是字段注入:

    public class RandomAuthenticator extends Security.Authenticator {
    
        private RandomService rs;   
    
        @Inject
        RandomAuthenticator(RandomService randomService) {
            this.rs = randomService;
        }
    
        @Override
        public String getUsername(Context context) {
            float randFloat = rs.nextFloat(); // Error! rs is always null
    
            if (randFloat > 0.1) {
                return "foo";
            }
    
            return null;
        }
    }
    
  2. # 2 楼答案

    public class RandomAuthenticator extends Security.Authenticator {
    
        private final RandomService rs;   
    
        public RandomAuthenticator(RandomService randomService) {
            this.rs = randomService;
        }
    
        ...
    }
    

    然后在Guice模块中使用@Providers方法:

    @Provides
    RandomAuthenticator provideRandomAuthenticator(RandomService randomService) {
        return new RandomAuthenticator(randomService);
    }