首页 > 解决方案 > Spring:@Controller 在 @Configuration 中创建 @Bean 之前调用

问题描述

我在使用@bean 的配置中将我自己的自定义映射添加到Environmnet,并使用控制器中的属性@Value("${test.property}") String xyz;
但我得到以下错误:

原因:java.lang.IllegalArgumentException:无法在 org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:180) 处解析值“${test.property}”中的占位符“test.property”~[spring-core -5.3.8.jar:5.3.8] 在 org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126) ~[spring-core-5.3.8.jar:5.3.8]

我在调试模式下了解到,在 @Configuration @Controller 类 bean 创建中 @Bean 创建之前正在发生。

任何人都可以对此提出建议。

配置类:
@Configuration
public class TempTestConfig {
static {
System.currentTimeMillis();
System.out.println("测试");
} @Autowired ConfigurableEnvironment 环境;

@Bean
public void testDemo(){
    MutablePropertySources propertySources = environment.getPropertySources();
    Map<String, Object> myMap = new HashMap<>();
    myMap.put("test.property", "myValue");
    propertySources.addFirst(new MapPropertySource("MY_MAP", myMap));
}

}

和控制器类
@Validated
@PreAuthorize("hasRole('test')")
@RequestMapping("/api/v1") @RestController
public class SummaryController {
static {
System.currentTimeMillis();
}

@Autowired<br />
SummaryService service;<br />

@Autowired<br />
Environment environment;

@Value("${test.property}")<br />
String xyz;<br />

  

@GetMapping(value="/summary/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public Mono<TEST> getSummary(@PathVariable("id") String id) {
    return service.getSummary(id);
}

}

标签: springconfiguration

解决方案


推荐阅读