简体   繁体   English

如何在 Spring 引导 CLI 应用程序中注册自定义转换器

[英]How register custom Converter in Spring Boot CLI application

I would like register in my spring boot command line app custom spring Converter but i can't solve it.我想在我的spring 引导命令行应用程序自定义 spring 转换器中注册,但我无法解决它。 Each solution what I found are for spring boot web app.我发现的每个解决方案都适用于 spring 启动 web 应用程序。 I think it has to be somehow possible.我认为它必须以某种方式成为可能。

My application is configured via property file.我的应用程序是通过属性文件配置的。 For loading property file into app we use spring run argument --spring.config.location with value path to our property file.要将属性文件加载到应用程序中,我们使用 spring 运行参数--spring.config.location和属性文件的值路径。

For easier usage in app I would like use enums for some properties.为了在应用程序中更容易使用,我想对某些属性使用枚举。 If user use in property value which isn't supported by Enum class.如果用户在 Enum class 不支持的属性值中使用。 App will throw exception应用程序将抛出异常

Caused by: java.lang.IllegalArgumentException: No enum constant com.actimize.amlperfreport.enums.OSFamily.window
    at org.springframework.boot.convert.LenientObjectToEnumConverterFactory$LenientToEnumConverter.findEnum(LenientObjectToEnumConverterFactory.java:93)
    at org.springframework.boot.convert.LenientObjectToEnumConverterFactory$LenientToEnumConverter.convert(LenientObjectToEnumConverterFactory.java:80)
    at org.springframework.boot.convert.LenientObjectToEnumConverterFactory$LenientToEnumConverter.convert(LenientObjectToEnumConverterFactory.java:61)
    at org.springframework.core.convert.support.GenericConversionService$ConverterFactoryAdapter.convert(GenericConversionService.java:436)
    at org.springframework.core.convert.support.ConversionUtils.invokeConverter(ConversionUtils.java:41)
    ... 107 common frames omitted

It isn't user friendly.它对用户不友好。 I would like use custom Converter for validate input values from property file before convert to enum, log my custom log message and set default value for errors.我想在转换为枚举之前使用自定义转换器验证属性文件中的输入值,记录我的自定义日志消息并设置错误的默认值。

Part of my property file for example:我的属性文件的一部分,例如:

ais.system.environment=windows
db.system.environment=windows
rcm.system.environment=unix
db.server.type=mssql
...

Class for store values from property file in app: Class 用于存储应用程序中属性文件中的值:

@Slf4j
@Getter
@Setter
@Configuration
public class ExecutionTemplate {

    @Value("#{'${ais.system.environment}'.toLowerCase()}")
    private OSFamily environmentAIS;
...

Custom Converter:自定义转换器:

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.converter.Converter;

@Slf4j
public class OSFamilyConverter implements Converter<String,OSFamily> {
    @Override
    public OSFamily convert(String source) {
        if(OSFamily.WINDOWS.getType().equals(source)){
            return OSFamily.WINDOWS;
        } else if(OSFamily.UNIX.getType().equals(source)){
            return OSFamily.UNIX;
        }
        log.error("[{}] isn't between supported operation system. App will use as operation system [{}]. Supporter operation systems are [{},{}].",
                source,OSFamily.UNIX.getType(),OSFamily.UNIX.getType(),OSFamily.WINDOWS.getType());
        return OSFamily.UNIX;
    }
}

Main class:主class:

@Slf4j
@RequiredArgsConstructor
@SpringBootApplication
public class AmlPerfReportApplication implements CommandLineRunner {

    private final ApplicationContext context;
    private final OrchestratorService orchestratorService;
    private final Messenger messenger;
    private JCommander jCommander;


    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(AmlPerfReportApplication.class);

        app.setBannerMode(Banner.Mode.LOG);
        app.run(args);
    }

    @Override
    public void run(String... args) throws Exception {
        Args arguments = new Args();
...

If i am right custom converter has to be register in main method before call run method.如果我是对的,自定义转换器必须在调用 run 方法之前在 main 方法中注册。 But i don't know how.但我不知道怎么做。

My app doesn't have web interface i can't use method addFormatter from WebMvcConfigurer How to register custom converters in spring boot?我的应用程序没有 web 接口我无法使用来自WebMvcConfigurer 的方法 addFormatter如何在 spring 启动中注册自定义转换器?

Could you please help me?请你帮助我好吗?

Converter seems to only work on properties bound to a ConfigurationProperties , but not @Value . Converter似乎只适用于绑定到ConfigurationProperties的属性,而不@Value

This works for me:这对我有用:

public enum OSFamily { }

@Component
@ConfigurationPropertiesBinding
public class OSFamilyConverter implements Converter<String, OSFamily> { }

@Component
@ConfigurationProperties(prefix = "system")
@Getter @Setter
class SystemProperties{
    private OSFamily ais;
    private OSFamily db;
    private OSFamily rcm;
}

...
// Then inject normally
@Autowired
MyConfigProperties systemProperties;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM