Spring 是否适用于 Azure 函数?
例如:内部代码使用“Autowired”注释的 Rest API(运行 mvn azure-functions:run 后,“myScriptService”上出现 NullPointerException)。
import java.util.*;
import com.microsoft.azure.serverless.functions.annotation.*;
import com.microsoft.azure.serverless.functions.*;
import com.company.ScriptService;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Azure Functions with HTTP Trigger.
*/
public class Function {
@Autowired
ScriptService myScriptService;
/**
* This function listens at endpoint "/api/hello". Two ways to invoke it using "curl" command in bash:
* 1. curl -d "HTTP Body" {your host}/api/hello
* 2. curl {your host}/api/hello?name=HTTP%20Query
*/
@FunctionName("myhello")
public HttpResponseMessage<String> hello(
@HttpTrigger(name = "req",
methods = "post",
authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,
final ExecutionContext context) {
context.getLogger().info("Java HTTP trigger processed a request.");
// Parse query parameter
String query = request.getQueryParameters().get("name");
String name = request.getBody().orElse(query);
if (name == null) {
return request.createResponse(400, "Please pass a name on the query string or in the request body");
} else {
return request.createResponse(200, "Hello, " + name + ", myScriptService.isEnabled(): " + myScriptService.isEnabled());
}
}
}
最佳答案
正如一些人在上面的评论中要求解决方案一样,我假设这个问题也可能与其他用户相关。
所以我认为 Spring Cloud Function 是这里的魔法词:除了其他一些要点(有关详细信息,请参阅 project page),它旨在在无服务器提供程序(除了Azure Functions,还支持 AWS Lambda 和 Apache OpenWhisk)。
所以你必须对你的项目进行一些修改:
添加 spring-cloud-function-adapter-azure 依赖项:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-function-adapter-azure</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
您的处理程序类需要一些额外的代码:
它应该是这样的:
@SpringBootApplication
@ComponentScan(basePackages = { "package.of.scriptservice" })
public class Function {
@Autowired
ScriptService myScriptService;
@FunctionName("myhello")
public HttpResponseMessage<String> hello(
@HttpTrigger(name = "req", methods = "post", authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,
final ExecutionContext context) {
// Your code here
}
public static void main(String[] args) {
SpringApplication.run(DemoFunctionHandler.class, args);
}
}
你可以找到一个完整的例子 here和 here
关于Spring 和 Azure 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49842681/