Java 如何从主类向Springbean注入属性
我在我的应用程序中使用spring,我能够将类路径上某个文件中的一些属性注入到我的应用程序中,并且一切都很完美。i、 eJava 如何从主类向Springbean注入属性,java,spring,Java,Spring,我在我的应用程序中使用spring,我能够将类路径上某个文件中的一些属性注入到我的应用程序中,并且一切都很完美。i、 e <bean class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer"> <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_O
<bean class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="searchContextAttributes" value="true" />
<property name="contextOverride" value="true" />
<property name="ignoreResourceNotFound" value="true" />
<property name="locations">
<list>
<value>classpath:application.properties</value>
</list>
</property>
</bean>
它也可以工作,我的问题是如何在spring上下文中插入属性文件位置,而不首先在那里,我想让我的应用程序可配置。如果我从
C:\dir
或/user/home/dir
执行我的应用程序,我假设在应用程序上下文中,值应该是C:\application.properties
或/user/home/dir/application.properties
如果我正确阅读了您的问题,您希望使用外部属性文件(即文件不在应用程序运行时类路径中)。如果是这种情况,则需要使用文件标记
<value>file:///c:\application.properties</value>
file:///c:\应用程序属性
您可以使用@Value
从环境中注入值。例如:
private someFoo;
@Value("${systemProperties.someFoo}")
public void setSomeParam(String someParam) {
this.someFoo = someParam;
}
我以前也遇到过类似的问题。我的要求是属性文件不捆绑在应用程序中(因此不在类路径中)。文件可以位于文件系统中的任何位置。 我是这样解决的
<bean class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="searchContextAttributes" value="true" />
<property name="contextOverride" value="true" />
<property name="ignoreResourceNotFound" value="true" />
<property name="locations">
<list>
<value>file://${APP_PROP_HOME}/application.properties</value>
</list>
</property>
</bean>
文件://${APP_PROP_HOME}/application.properties
Spring解析${APP_PROP_HOME}到存储在相应env属性中的值,并且在运行时配置您的应用程序。我将如何从主类将其注入到应用程序上下文?您可以使用类似的方法注入属性位置,确保将此属性添加到属性配置器,您可以执行此操作PropertyPlaceholderConfigurer=(PropertyPlaceholderConfigurer)ctx.getBean(PropertyPlaceholderConfigurer.class);资源rsc=新文件系统资源(“file:///C:\\应用程序\\one.properties”);配置器.setLocation(rsc),我不知道为什么要这样做,但如果在spring容器启动后插入属性文件,则无法在上下文文件中使用属性。我无法在我的PostConstructionHook中使用这些属性。访问这些变量的要求是什么?
<bean class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="searchContextAttributes" value="true" />
<property name="contextOverride" value="true" />
<property name="ignoreResourceNotFound" value="true" />
<property name="locations">
<list>
<value>file://${APP_PROP_HOME}/application.properties</value>
</list>
</property>
</bean>