0
点赞
收藏
分享

微信扫一扫

SpringBoot 官方文档示例:(29)application.properties中的类型转换

MaxWen 2022-05-01 阅读 54
spring boot

一、需求:已经定义了一个普通实体类,要在application.properties中直接通过字符串给这个类注入值。
1.实体类:

package cn.edu.tju.domain;

public class Author {
    private String firstName;
    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

2.配置类:
package cn.edu.tju.config;

import cn.edu.tju.domain.Author;
import cn.edu.tju.domain.MyPojo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.Map;

@Configuration
@ConfigurationProperties(“my.test”)
public class AppConfig6 {
private Author author;

public Author getAuthor() {
    return author;
}

public void setAuthor(Author author) {
    this.author = author;
}

}

3.application.properties 中的配置:

my.test.author=paul schools

如果直接这样启动的话,程序直接报错:

Failed to bind properties under 'my.test.author' to cn.edu.tju.domain.Author:

    Reason: org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [cn.edu.tju.domain.Author]

因为spring boot不知道如何从一个String类型的值(paul schools)转换为Author类型,因此要定义相应的转换器并进行配置
4.定义转换器类:

package cn.edu.tju.config;

import cn.edu.tju.domain.Author;
import org.springframework.core.convert.converter.Converter;

public class MyConversionService implements Converter<String, Author> {
    @Override
    public Author convert(String source) {
        String[] names=source.split(" ");
        if(names.length<2){
            throw new RuntimeException("不正确的参数格式");
        }
        Author author=new Author();
        author.setFirstName(names[0]);
        author.setLastName(names[1]);
        return  author;
    }
}

5.配置名为conversionService的bean:

package cn.edu.tju.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ConversionServiceFactoryBean;
import org.springframework.core.convert.ConversionService;

import java.util.HashSet;
import java.util.Set;

@Configuration
public class MyConfig {
    @Bean("conversionService")
    public ConversionService getConversion(){
        ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean();
        Set<MyConversionService> serviceSet=new HashSet<>();
        serviceSet.add(new MyConversionService());
        bean.setConverters(serviceSet); //add converters
        bean.afterPropertiesSet();
        return bean.getObject();
    }
}

举报

相关推荐

0 条评论