1.加载配置文件
@Bean
public static PropertySourcesPlaceholderConfigurer properties() throws FileNotFoundException {
try {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
yaml.setResources(new ClassPathResource("application.yaml"));
configurer.setProperties(Objects.requireNonNull(yaml.getObject()));
return configurer;
} catch (IllegalStateException e) {
Throwable cause = e.getCause();
if (cause instanceof FileNotFoundException){
throw (FileNotFoundException) e.getCause();
}
throw e;
}
}
2.启动
@ComponentScan(basePackages = "lab.service")
@EnableAutoConfiguration
public class BandJob {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BandJob.class,LoadConfig.class);
CalculateResultHandlerService calculateResultHandlerService = applicationContext.getBean(CalculateResultHandlerService.class);
calculateResultHandlerService.handlerBand();
System.exit(0);
}
}
java本身不适合写脚本,多是作为服务器启动的,但是如果能够让脚本形式的java使用spring的组件,那么就可以复用很多东西,减少一些重复的代码
这里没引入spring日志组件,因此手动写logback.xml控制日志输出
logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
<!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径-->
<!-- <property name="LOG_HOME" value="D:\log" />-->
<!-- 控制台输出 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>%white(%d{yyyy-MM-dd HH:mm:ss.SSS}) [%thread] %highlight(%-5level) %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<!-- 按照每天生成日志文件 -->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">-->
<!-- <!–日志文件输出的文件名–>-->
<!-- <FileNamePattern>${LOG_HOME}/Main.log.%d{yyyy-MM-dd}.log</FileNamePattern>-->
<!-- <!–日志文件保留天数–>-->
<!-- <MaxHistory>30</MaxHistory>-->
<!-- </rollingPolicy>-->
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>%white(%d{yyyy-MM-dd HH:mm:ss.SSS}) %highlight(%lsn) [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>utf8</charset>
</encoder>
<!--日志文件最大的大小-->
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
</appender>
<!-- 日志输出级别 -->
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
或者也可以直接使用Spring的配置
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml" />
</configuration>