在实际项目中,为方便系统的更改,我们常常将一些变量的值放到资源文件中,比方说系统用到的调用服务的IP地址,端口,用户名和密码以及一些路径等。为方便我们轻松获得这些放在资源文件中的变量,spring则为我们提供了读取xxx.properties文件的内容的很好的方法。如下:
1、在资源文件xxx. properties中设置一些变量的值
#FTP configFTP_ADDRESS=192.168.40.128FTP_PORT=21FTP_USERNAME=ftpuserFTP_PASSWORD=ftpuserFTP_BASE_PATH=/home/ftpuser/www/images#imageServer configIMAGE_BASE_URL=http://192.168.40.128/images
2、在applicationContext中配置读取xxx. properties文件的语句,如下:
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:resource/*.properties" />
3、 在service中通过注入方式获取资源文件变量的值:
/*** 图片上传实现类* @author liujie**/@Servicepublic class PictureServiceImpl implements PictureService {//注意{}中的变量应该与资源文件中的变量名一致,这样就可以将值取出来直接应用了
@Value("${FTP_ADDRESS}")private String FTP_ADDRESS;@Value("${FTP_PORT}")private Integer FTP_PORT;@Value("${FTP_USERNAME}")private String FTP_USERNAME;@Value("${FTP_PASSWORD}")private String FTP_PASSWORD;@Value("${FTP_BASE_PATH}")private String FTP_BASE_PATH;@Value("${IMAGE_BASE_URL}")private String IMAGE_BASE_URL;
}