在控制器中注入属性值的最佳方法是什么?

Rih*_*rds 0 java spring-annotations spring-3

这是如何从属性文件中在控制器中注入属性的最简单方法吗?然后需要在每个需要一些属性的控制器上导入属性文件.在像我这样的项目中有大约30个控制器,其中10个需要这个国家属性,我觉得它看起来很混乱.我是否理解@Value正确的使用方法?

@Controller
@RequestMapping(value = "/simple")
@ImportResource("classpath:/META-INF/properties-config.xml")
public class SimpleController {

    private @Value("#{exampleProperties['simple.country']}") String country;

}
Run Code Online (Sandbox Code Playgroud)

properties-config.xml (跳过xml和schema的东西)

<beans>
    <util:properties id="exampleProperties" location="classpath:/simple.properties" />
</beans>
Run Code Online (Sandbox Code Playgroud)

此外,当尝试在多个控制器中导入properties-config.xml资源时,我会收到此类消息.它似乎不是正确的方法,但我无法找到一个更好的..

01 Apr 2011 04:52:29,859 INFO  org.springframework.beans.factory.support.DefaultListableBeanFactory []: Overriding bean definition for bean 'exampleProperties': replacing [Generic bean: class [org.springframework.beans.factory.config.PropertiesFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Generic bean: class [org.springframework.beans.factory.config.PropertiesFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
Run Code Online (Sandbox Code Playgroud)

axt*_*avt 8

我认为你的方法在这种情况下过于复杂.典型的方法是使用<context:property-placeholder>.你宣布

<context:property-placeholder location = "classpath:/simple.properties" />
Run Code Online (Sandbox Code Playgroud)

在一个地方,并在控制器中使用其属性

private @Value("${simple.country}") String country;
Run Code Online (Sandbox Code Playgroud)

另外我认为使用@ImportResource这种方式不是一个好主意,它违反了依赖注入原则 - 这些属性是控制器工作的上下文的一部分,因此控制器不应该知道它们是如何加载的.