自定义convert 从application.properties读取内容,转成自定义类型

Spring官网 Convert

示例代码

  • AppConfig
@PropertySource("classpath:application.properties")
public class AppConfig {
    @Bean
    public ConversionService conversionService() {
        DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService();
        conversionService.addConverter(new MyCustomConverter());
        return conversionService;
    }
}
  • MyCustomConverter.java
public class MyCustomConverter implements Converter<String, List> {
    @Override
    public List convert(String s) {
        System.out.println(s);
        return Arrays.asList(s);
    }
}
  • MovieRecommender .java
public class MovieRecommender {
    private final List grade;
    private final String name;

    public MovieRecommender(@Value("${catalog.grade}") List grade, @Value("${catalog.name}") String name) {
        this.grade = grade;
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public List getGrade() {
        return grade;
    }
}
  • SpringMain .java
public class SpringMain {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("config.xml");
        MovieRecommender bean = context.getBean(MovieRecommender.class);
        System.out.println(bean);
        System.out.println(bean.getGrade());
        System.out.println(bean.getName());
    }
}
  • config.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       https://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <context:annotation-config/>
    <bean class="org.example.mavenjavademo.spring.MovieRecommender" id="movieRecommender"/>
    <bean class="org.example.mavenjavademo.spring.AppConfig" id="appConfig"/>
beans>
  • application.properties
catalog.grade=ab,cd,ef
catalog.name=Movie
  • 运行结果
    自定义convert 从application.properties读取内容,转成自定义类型_第1张图片

你可能感兴趣的:(Spring)