读取配置文件获取变量
1 Java代码直接读取
Properties pro = new Properties();
InputStream ins = Application.class.getClassLoader().getResourceAsStream("ip.properties");
pro.load(ins);
String ipAddr = pro.getProperty("hostIp");
System.out.println(ipAddr);
2 @Value的方式
在application-context.xml 如下配置
<!-- 加载属性文件 -->
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
<value>classpath:pdsci.properties</value>
</list>
</property>
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="properties" ref="configProperties" />
</bean>
代码中使用
@Value("#{configProperties['remote.refresh.port']}")
private String remoteRefreshPort;
3 bean的方式
<bean class="org.springframework.web.context.support.ServletContextAttributeExporter">
<property name="attributes">
<map>
<entry key="name" value="123"/>
<entry key="app" value="45"/>
</map>
</property>
</bean>
ServletContext context = this.getServletContext();
System.out.println(context.getAttribute("name"));