代码之家  ›  专栏  ›  技术社区  ›  Stoopkid

无法从异步方法获取应用程序属性

  •  1
  • Stoopkid  · 技术社区  · 8 年前
    @Service
    public Class SomeService {
    
        private SomeServiceAsync someServiceAsync = new SomeServiceAsync();
    
        ...
    
        public String DoAThing() {
            CompletableFurute<String> future = someServiceAsync.GetAString();
            return future.get();
        }
    }
    
    @Service
    @EnableAsync
    public Class SomeServiceAsync {
    
        @Value("${someProp1}")
        private String someProp1;
    
        @Autowired
        private Environment env;
    
        ...
    
        @Async
        public CompletableFuture<String> GetAString() {
            System.out.println(someProp1); // returns null
            String someProp2 env.getProperty("someProp2"); // throws null pointer exception
    
            return CompletableFurute.completedFuture("blablabla");
        }
    }
    

    我的问题很简单,在使某些方法异步运行之后,我无法访问应用程序属性。在我尝试执行该方法并从@Value获取null或env为null之前,没有任何失败。

    该方法在使其异步之前工作,当我不访问应用程序属性时,异步版本工作正常。

    1 回复  |  直到 8 年前
        1
  •  2
  •   df778899    8 年前

    看起来问题是 new SomeServiceAsync() ,而不是 @Autowired .

    我自己也犯过很多次同样的错误。

    推荐文章