更新时间:2022-12-06 09:40:01
首先,您的Test
类应使用@Component
进行注释,以便在春季之前将其注册为bean(还请确保所有类位于您的主程序包下-主程序包位于带有@SpringBootApplication
注释的类).
First of all your Test
class should be annotated with @Component
in order for it to be registered as a bean by spring (also make sure all your classes are under your main package - the main package is where a class that is annotated with @SpringBootApplication
reside).
现在,您应该将所有属性移至application.yml
(src/main/resources/application.yml
),该属性将由Spring Boot自动选择(请注意,该属性应为.yml
而不是.yaml
)或注册自定义的PropertySourcesPlaceholderConfigurer
.
Now you should either move all your properties to application.yml
(src/main/resources/application.yml
), that is picked automatically by spring boot (note that it should be .yml
instead of .yaml
or register a custom PropertySourcesPlaceholderConfigurer
.
PropertySourcesPlaceholderConfigurer
的示例:
@Bean
public static PropertySourcesPlaceholderConfigurer PropertySourcesPlaceholderConfigurer() throws IOException {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
MutablePropertySources propertySources = new MutablePropertySources();
Resource resource = new DefaultResourceLoader().getResource("classpath:application.yml");
YamlPropertySourceLoader sourceLoader = new YamlPropertySourceLoader();
PropertySource<?> yamlProperties = sourceLoader.load("yamlProperties", resource, null);
propertySources.addFirst(yamlProperties);
configurer.setPropertySources(propertySources);
return configurer;
}
现在应该将属性加载到Spring的环境中,并且可以将它们与@Value
一起注入到您的bean中.
Now your properties should be loaded to spring's environment and they will be available for injection with @Value
to your beans.