如何在 Spring 将 Vaadin UI 连接到 Amazon S3 服务?

问题描述 投票:0回答:1

我正在使用 Vaadin 构建一个 Web 界面,该界面显示 Vaadin 网格组件中 Amazon S3 存储桶中的对象列表。我的服务工作正常,但每次尝试将 S3 服务中的对象列表添加到网格时,我都会收到 NullPointerException。

这是 S3 服务: S3 Service

我在测试类上使用 spring CommandLineRunner 接口测试了我的服务。这是测试类: Test Class

每当我运行应用程序时,我都会看到控制台上列出的 S3 存储桶中的项目列表: Console Output

但是每当我尝试将列表项添加到 Vaadin 网格并且控制台上记录 BeanCreationException 时,同一服务都会在浏览器上引发 NullPointerException:

BeanCreationException NullPointerException

这里是S3Service.java

@Service
public class S3Service {
    @Autowired
    private AmazonS3 s3Client;
    @Value("${aws.s3.bucket.name}")
    private String bucketName;
    public List<String> listObjects() {
        ObjectListing objectListing=s3Client.listObjects(bucketName);
        return objectListing.getObjectSummaries()
                .stream()
                .map(S3ObjectSummary::getKey)
                .collect(Collectors.toList());
    }
}

TestFeatureClass.java

@Component
public class TestFeatureClass implements CommandLineRunner {
    @Autowired
    private S3Service s3Service;
    @Override
    public void run(String... args) throws Exception {
        System.out.println(s3Service.listObjects());
    }
}

文档管理系统视图.java

@PageTitle("Documents")
@Route(value = "api/v1/files/list",layout = MainLayout.class)
@Uses(Icon.class)
public class DocumentManagementSystemView extends VerticalLayout {
    @Autowired
    public S3Service s3Service;
    Grid<String> grid;
    public DocumentManagementSystemView() {

        this.grid=new Grid<>(String.class,false);
        configureGrid();

        add(grid);
        updateList();

    }
    private void configureGrid() {
        grid.setColumns("Filename");
    }
    private void updateList() {
        grid.setItems(s3Service.listObjects());
    }
}
java spring amazon-s3 vaadin vaadin24
1个回答
0
投票

我看到的第一个问题是,如果您打算在构造函数期间使用注入的 bean,则应该使用构造函数注入而不是字段注入。这应该可以修复您的 NullPointerException。

@PageTitle("Documents")
@Route(value = "api/v1/files/list",layout = MainLayout.class)
@Uses(Icon.class)
public class DocumentManagementSystemView extends VerticalLayout {
    
    private S3Service s3Service;
    private Grid<String> grid;
    
    public DocumentManagementSystemView(S3Service s3Service) {
        this.s3Service = s3Service;
        ...
    }
}

我看到的第二个问题是您在 String 类型的 Grid 上使用

grid.setColumns("Filename")
。这将尝试在 String 类中查找名为“Filename”的属性并将其呈现在列中。我假设您想要一个标题为“文件名”的列。这是它的工作原理:

// instead of "str -> str" you could also use Function.identity() if that more readable to you
grid.addColumn(str -> str).setHeader("Filename");
© www.soinside.com 2019 - 2024. All rights reserved.