Java 如何仅使用注释读取控制器中的属性文件?春季MVC
如何仅使用注释读取控制器中的属性文件 属性文件包含(env.Properties): 弹簧控制器:Java 如何仅使用注释读取控制器中的属性文件?春季MVC,java,spring,spring-mvc,Java,Spring,Spring Mvc,如何仅使用注释读取控制器中的属性文件 属性文件包含(env.Properties): 弹簧控制器: @Controller @RequestMapping("/kap/*") @SessionAttributes({"user", "KapForm", "activity"}) public class KapController { @Value("${document.portal.path}") private String URL; } 别的什么也没做。在XML中,我们使用占位符,我
@Controller
@RequestMapping("/kap/*")
@SessionAttributes({"user", "KapForm", "activity"})
public class KapController {
@Value("${document.portal.path}")
private String URL;
}
别的什么也没做。在XML中,我们使用占位符,我不知道如何在其中介绍占位符。所以我得到了例外
Injection of autowired dependencies failed;
你可以通过两种方式实现它 选项1 在config类中放入
@PropertySource
,并为propertysourcesplaceconfigurer
定义一个bean,如下所示-
@Configuration
@PropertySource("classpath:someFile.properties")
public class SampleConfig {
// other configs...
@Bean
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
选项2
在config类中,直接为PropertyPlaceHolderConfigure
指定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;
}
}
请注意,PlaceHolder的bean定义需要是静态的
(以下摘录)
必须特别考虑返回SpringBeanFactoryPostProcessor
(BFPP)类型的@Bean
方法。由于BFPP对象必须在容器生命周期的早期进行实例化,因此它们可能会干扰@Autowired
、@Value
和@PostConstruct
类中注释的处理。为了避免这些生命周期问题,请将BFPP返回的@Bean
方法标记为static
另一个出路是
import org.springframework.context.MessageSource;
@Autowired
private MessageSource messageSource;
cutiePie = messageSource.getMessage("cutie.pie.property", new Object[] {},"cutie.pie.property", LocaleContextHolder.getLocale());
您是否在bean定义文件中为
env.properties
声明了util:properties
?如果您可以发布配置文件,将很容易得到帮助you@xyz:没有配置文件。这都是注释。我不知道在哪里声明util:propertiesThanks。我可以在控制器中为相同的对象创建内部类并在外部类中使用吗?因为这只在一个控制器中使用?最好的办法是,若我能像上面所示的那个样自动连线,那个么其他模块也会遵循这个范例。
import org.springframework.context.MessageSource;
@Autowired
private MessageSource messageSource;
cutiePie = messageSource.getMessage("cutie.pie.property", new Object[] {},"cutie.pie.property", LocaleContextHolder.getLocale());