gpt4 book ai didi

java - 如何仅使用注释读取 Controller 中的属性文件? Spring MVC

转载 作者:行者123 更新时间:2023-11-30 08:11:03 26 4
gpt4 key购买 nike

如何仅使用注释读取 Controller 中的属性文件?

属性文件包含(env.properties):

 document.portal.path=http://flana.gost.com/service

Spring Controller :

@Controller
@RequestMapping("/kap/*")
@SessionAttributes({"user", "KapForm", "activity"})
public class KapController {
@Value("${document.portal.path}")
private String URL;
}

没有做任何其他事情。在 XML 中,我们经常使用占位符,但我不知道如何在其中引入。所以我遇到了异常(exception)。

Injection of autowired dependencies failed; 

最佳答案

您可以通过两种方式实现它

选项 1

在配置类中放置@PropertySource并为PropertySourcesPlaceholderConfigurer定义一个bean,如下 -

@Configuration
@PropertySource("classpath:someFile.properties")
public class SampleConfig {

// other configs...

@Bean
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}

选项 2

在配置类中直接为PropertyPlaceholderConfigurer指定bean,并将属性文件的名称提供为ClassPathResource

@Configuration
public class SampleConfig {

// other configs...

@Bean
public static PropertyPlaceholderConfigurer placeHolderConfigurer(){
PropertyPlaceholderConfigurer placeHolderConfigurer = new PropertyPlaceholderConfigurer();
ClassPathResource[] cpResources = new ClassPathResource[]
{ new ClassPathResource( "someFile.properties" ) };
placeHolderConfigurer.setLocations(cpResources);
placeHolderConfigurer.setIgnoreUnresolvablePlaceholders(true);
return placeHolderConfigurer;
}
}

请注意,占位符的 bean 定义必须是静态,如 java docs 所示。 (摘录如下)

Special consideration must be taken for @Bean methods that return Spring BeanFactoryPostProcessor (BFPP) types. Because BFPP objects must be instantiated very early in the container lifecycle, they can interfere with processing of annotations such as @Autowired, @Value, and @PostConstruct within @Configuration classes. To avoid these lifecycle issues, mark BFPP-returning @Bean methods as static.

关于java - 如何仅使用注释读取 Controller 中的属性文件? Spring MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30389450/

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