0

我想插入 Spring Basics: Dynamically Inject Values With Spring's @Value。我该怎么做?

我尝试了代码

@Value("#{{2: 'Catch22', 22: '1984', 32: 'Pride and Prejudice'}}")

但我有例外

private Map <Integer,String>studentTeacherMap;
@Value("#{{2: 'Catch22', 22: '1984', 32: 'Pride and Prejudice'}}")
public Map<Integer, String> loki()
return studentTeacherMap;

我希望输出是

2= Catch22, 22= 1984, 32= Pride and Prejudice 

但最终出现了例外:

Cannot handle (123) '{'

4

1 回答 1

1

如果要将此映射注册为 Bean,请考虑将其放入带@Configuration注释的类中:

@Configuration
public class AppConfiguration {
    @Value("#{{2: 'Catch22', 22: '1984', 32: 'Pride and Prejudice'}}")
    private Map<Integer, String> lokiMap;

    @Bean
    public Map<Integer, String> lokiMap() {
        return lokiMap;
    }
}

并在你想使用它的类中注入这个bean:

@Autowired
private Map<Integer, String> lokiMap;

或者你可以直接使用map而不将其声明为bean,但在这种情况下你不需要@Autowired注释,只需放在@Valuemap下:

@Value("#{{2: 'Catch22', 22: '1984', 32: 'Pride and Prejudice'}}")
private Map<Integer, String> lokiMap;
于 2019-06-15T13:22:11.360 回答