首先贴一下传统用法和@Value注解的用法示例:
https://blog.csdn.net/yh_zeng2/article/details/76222905
上面这篇博客里介绍了通过xml方式和注解方式获取properties属性的方法,通常看完这篇博客就已经可以解决大部分情况了。但是有一种极端的情况就是你的项目里没有applicationContext.xml文件。这时候你需要获取配置怎么办呢?直接先上代码
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import java.util.Properties;
@Slf4j
public class CountTaskService {
public static void main(String[] args) throws Exception{
Resource resource = new ClassPathResource("/task.properties");
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
Object o = properties.get("countOnlineUser.perfix");
log.info(o.toString());
}
}
运行示例如下:
项目目录结构如下:
properties配置如下:
如果有多个文件,在代码里读取多个就可以了,如果不在resources这一级目录下,记得带上目录