Ven*_*nus 5 spring azure-functions
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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
由于有些人在上面的评论中寻求解决方案,我假设这个问题也可能与其他用户相关。
所以我认为 Spring Cloud Function 是一个神奇的词:除了其他一些点(有关详细信息,请参阅项目页面)之外,它的目标是在无服务器提供程序(除了 Azure 之外)上启用 Spring Boot 功能(例如依赖项注入,您正在寻找的功能)函数,还支持 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>
Run Code Online (Sandbox Code Playgroud)
您的处理程序类需要一些额外的代码:
它应该看起来像这样:
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2881 次 |
| 最近记录: |