从其他类调用时,在自动装配的类上获取Null

时间:2018-08-23 15:05:47

标签: java spring spring-mvc spring-boot

Test.java

import org.apache.http.client.methods.HttpGet

import play.api.libs.json._
import org.apache.http.impl.client.DefaultHttpClient


object main extends App {
  val url = "https://api.binance.com/api/v1/aggTrades?symbol=ETHBTC"

  val httpClient = new DefaultHttpClient()
  val httpResponse = httpClient.execute(new HttpGet(url))
  val entity = httpResponse.getEntity()
  val content = ""

  if (entity !=null) {
    val inputStream = entity.getContent()
    val result = io.Source.fromInputStream(inputStream).getLines.mkString
inputStream.close

    println("REST API: " + url)
    val json: JsValue = Json.parse(result)


    var prices = (json\\"p")

    println(prices.map(_.toString()).map(_.toDouble))

  }
}

这是我的工厂班级

@Service
public class Test {

public void Testing() {
    System.out.println("inside testing");
}
}

这是我的ABCIMP.java类

@Service
 public class ClaimFactory extends BaseClaimFactory {

   @Autowired
   ClaimProvider claimProvider;

@Override
public ClaimProvider getClaimRequest( String type) throws Exception {

    if (type.equals(ClaimProviderEnums.ABC.toString())) {

         claimProvider = new ABCIMP();
    }

    return claimProvider;
}

}

}

我这样打电话

@Service
public class ABCIMP implements ClaimProvider {

@Autowired
Test test;

public void claimRequest(){
      test.testing();
   }

我不知道为什么我在行 claimProviders=baseClaimFactory.getClaimRequest(); claimProviders.claimRequest(); 上得到java.lang.NullPointerException吗?有人知道为什么这会导致中断,并且在我打电话时它能正常工作吗?    test.testing()

1 个答案:

答案 0 :(得分:0)

您已使用ABCIMP创建了new ABCIMP();实例。除非您已配置AspectJ代理,否则Spring Framework不会处理使用Java new运算符创建的对象。

请勿创建新实例,仅使用@Autowired从Spring上下文中获取现有实例。完全删除ClaimFactory类,您将重复Spring的工作。如果您需要在运行时获取实例:

@Autowired
private ApplicationContext ctx;

...

if (type.equals(ClaimProviderEnums.ABC.toString())) {
     return ctx.getBean(ABCIMP.class);
}