-
pom文件
- slf4j-api
- slf4j-log4j12
- lombok
- sl4j-simple 在main中注意去掉scope
-
在resources下新建的日志记录文件
# Set root logger level to error log4j.rootLogger=INFO, Console, File ###### Console appender definition ####### # All outputs currently set to be a ConsoleAppender. log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.layout=org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{3}] %m%n #log4j.appender.Console.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c] %m%n ###### File appender definition ####### log4j.appender.File=org.apache.log4j.DailyRollingFileAppender log4j.appender.File.File=spring.log log4j.appender.File.Append=false log4j.appender.File.layout=org.apache.log4j.PatternLayout log4j.appender.File.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c] %m%n
-
main方法中
由于main方法是静态方法,所以需要使用
类名.class.getClassLoader().getResourcesAsStream("properties.properteis");
eg:
public static void main(String[] args) throws IOException { Logger logger = LoggerFactory.getLogger(App.class.getClass()); Properties properties = new Properties(); InputStream inputStream = App.class.getClassLoader().getResourceAsStream("properties.properties"); properties.load(inputStream); List<String> list = new ArrayList<>(); list.add("username"); list.add("password"); for (String key : list) { Object o = properties.get(key); logger.info("param is : {}, valaue is : {}", key, o); } }
-
在非静态方法中
使用
this.getClass().getResourcesAsStream("properties.properties");
即可, eg:
public void loadProperties(String filename, List<String> param) throws IOException { Properties properties = new Properties(); InputStream inputStream = this.getClass().getResourceAsStream(filename); properties.load(inputStream); for (String key : param) { Object o = properties.get(key); log.info("param is : {}, valaue is : {}", key, o); } }