gpt4 book ai didi

spring-mvc - 使用静态方法的基于 Spring Java 的配置

转载 作者:行者123 更新时间:2023-12-03 23:29:33 24 4
gpt4 key购买 nike

任何人都可以建议为什么我们需要使用 声明 PropertySourcesPlaceholderConfigurer bean静态 方法 ?我刚刚发现,如果我在下面使用非静态,那么 url 将被设置为空值,而不是从属性文件中获取 -

@Value("${spring.datasource.url}")
private String url;

@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfig(String profile) {
String propertyFileName = "application_"+profile+".properties";
System.out.println(propertyFileName);
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
configurer.setLocation(new ClassPathResource(propertyFileName));
return configurer;
}

@Bean
@Profile("local")
public static String localProfile(){
return "local";
}

@Bean
@Profile("prod")
public static String prodProfile(){
return "prod";
}

最佳答案

PropertySourcesPlaceholderConfigurer对象负责解析 @Value针对当前 Spring Environment 及其一组 PropertySource 的注释。 PropertySourcesPlaceholderConfigurer类实现 BeanFactoryPostProcessor .在容器生命周期中,一个 BeanFactoryPostProcessor对象必须早于 @Configuration 的对象被实例化-带注释的类。

如果您有 @Configuration -带有实例方法的带注释的类返回 PropertySourcesPlaceholderConfigurer对象,则容器无法实例化PropertySourcesPlaceholderConfigurer对象而不实例化 @Configuration -带注释的类对象本身。在这种情况下,@Value无法解决,因为PropertySourcesPlaceholderConfigurer @Configuration的对象实例化时对象不存在-带注释的类。因此,@Value -annotated 字段采用默认值,即 null .

请参阅 @Bean 的“引导”部分javadoc想要查询更多的信息。

关于spring-mvc - 使用静态方法的基于 Spring Java 的配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31763257/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com