如何在@Values注释中动态注入值? (Spring Java)

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

application.properties 包含给定的信息:

book.name1 = War and Piece
book.author1 = Leo Tolstoy
book.name2 = Crime and Punishment
book.author2 = Dostoevsky 
book.name3 = To Kill a Mockingbird
book.author3 = Harper Lee

还有一个 Book.java,它从文件中获取值

public class Book {
    String name;
    String author;
    static int bookid = 0;
    
    public Book(){bookid++;}
    
    @Value ("${book.name.concat(bookid)}")
    public void setName(String name)
    {this.name = name;}
    
    @Value ("${book.author.concat(bookid)}")
    public void setAuthor(String name)
    {this.author = author;}
    
    public String getBook()
    {return name + " by " + author;}
}

最后一个类包含书籍的数组列表

public class UniversityLibrary implements Library{
    List<Book> books;
    public UniversityLibrary(ArrayList<Book> books) //books are injected by ConfigClass
    {
        this.books = new ArrayList<>();
        for (Book bok: books)
        {this.books.add(bok);}
    }
}

System.out.println(ubilibrary.getBook(1)) 的结果是 ${book.name.concat(bookid)} by ${book.author.concat(bookid)} - 正如预期的那样,但不满足任务。创建一本书也不会真正帮助解决这种情况。

没有找到正确的语法来完成这项工作。我希望 Value 中的表达式从 bookid 中获取值并将其与 ${book.name..} 连接以获得结果 @Value("${book.name1}") 等...

java spring
1个回答
0
投票

可以用

@ConfigurationProperties

如果您拥有以下属性:

books[0].name = War and Piece
books[0].author = Leo Tolstoy
books[1].name = Crime and Punishment
books[1].author = Dostoevsky 
books[2].name = To Kill a Mockingbird
books[2].author = Harper Lee

您可以将这些属性自动连接到

List<Book>
:

@ConfigurationProperties
@Component // we either have to define it as component or specifically instruct Spring to scan for this with `@ConfigurationPropertiesScan`
public class BookProperties {

    private List<Book> books;

    // IMPORTANT! without a setter, spring won't bind the values
    public void setBooks(List<Book> books) {
        this.books = books;
    }

    // getter
}

之后您可以在任何需要的地方自动连接

BookProperties
并访问图书列表 (
books
)

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.