Bootstrap

Spring @Value注解的魔法:属性注入与类型转换实例解析

在Spring框架中,@Value注解是一个强大的工具,它允许我们将外部配置文件中的值注入到Spring管理的Bean中。不仅如此,Spring还能根据字段类型自动进行类型转换。本文将通过两个实例,详细解析@Value注解的使用及其类型转换的魔法。

实例一:货币类型的注入

首先,我们来看一个简单的货币类型注入的例子。假设我们有一个配置文件app.properties,其中定义了货币类型和价格:

theCurrency=PLN
thePrice=12,323.7654

在Spring中,我们可以这样注入这些值:

package com.logicbig.example;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import java.util.Currency;

public class ValueAnnotationExample {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
        ClientBean bean = context.getBean(ClientBean.class);
        bean.doSomething();
    }

    @Configuration
    @PropertySource("classpath:app.properties")
    public static class Config {
    }

    public static class ClientBean {
        @Value("${theCurrency}")
        private Currency currency;

        public void doSomething() {
            System.out.printf("The currency from prop file is %s%n", currency);
            System.out.printf("The currency name is %s%n", currency.getDisplayName());
        }
    }
}

输出结果将是:

The currency from prop file is PLN  
The currency name is Polish Zloty  

实例二:自定义日期类型的注入

接下来,我们来看一个自定义日期类型注入的例子。我们同样有一个配置文件app.properties,其中定义了交易日期:

theTradeDate=2016-9-14

在Spring中,我们可以这样注入并自定义日期格式:

package com.logicbig.example;
import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.CustomEditorConfigurer;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import java.text.SimpleDateFormat;
import java.util.Date;

public class ValueAnnotationExample2 {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
        ClientBean bean = context.getBean(ClientBean.class);
        bean.doSomething();
    }

    @Configuration
    @PropertySource("classpath:app.properties")
    public static class Config {
        @Bean
        public ClientBean clientBean() {
            return new ClientBean();
        }

        @Bean
        public static CustomEditorConfigurer customEditorConfigurer() {
            CustomEditorConfigurer cec = new CustomEditorConfigurer();
            cec.setPropertyEditorRegistrars(new PropertyEditorRegistrar[]{new MyCustomBeanRegistrar()});
            return cec;
        }
    }

    public static class ClientBean {
        @Value("${theTradeDate}")
        private Date tradeDate;

        public void doSomething() {
            System.out.printf("The trade date from prop file is %s%n", tradeDate);
        }
    }

    public static class MyCustomBeanRegistrar implements PropertyEditorRegistrar {
        @Override
        public void registerCustomEditors(PropertyEditorRegistry registry) {
            SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
            dateFormatter.setLenient(false);
            registry.registerCustomEditor(Date.class, new CustomDateEditor(dateFormatter, true));
        }
    }
}

输出结果将是:

The trade date from prop file is Wed Sep 14 00:00:00 CDT 2016  

总结

通过这两个实例,我们可以看到Spring的@Value注解不仅能够实现简单的字符串注入,还能通过自定义PropertyEditor来实现复杂的类型转换。这使得我们可以轻松地将配置文件中的值注入到Spring Bean中,并且保持代码的灵活性和可维护性。Spring的这种类型转换功能,极大地简化了配置管理,使得开发者可以专注于业务逻辑的实现。

;