SpringBoot自动装配

  1. 配置文件的读取
  2. 自动装配

说明:

  1. 需要lombok插件

  2. Spring Boot 2.1.4.RELEASE

  3. 需要配置的信息如下,Spring 中配置信息文件为system.properties,Spring Boot中直接在applicaiton.properties

    1
    system.name = test

配置文件

实现方式

Spring XML方式

property-placeholder方式
  1. XML配置application-xml-property.xml

    1
    <context:property-placeholder location="classpath:system.properties"/>
  2. 配置类XmlConfiguration

    1
    2
    3
    4
    5
    6
    7
    8
    9
    @Setter
    @Getter
    @Component
    @ImportResource("classpath:/application-xml-property.xml")
    public class XmlConfiguration {

    @Value("${system.name}")
    private String systemName;
    }
PropertyPlaceholderConfigurer方式
  1. XML配置application-property-configurer.xml

    1
    2
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">     <property name="location" value="classpath:system.properties"/>
    </bean>
  2. 配置类PropertyPlaceholderConfiguration

1
2
3
4
5
6
7
8
9
@Setter
@Getter
@Component
@ImportResource("classpath:/application-property-configurer.xml")
public class PropertyPlaceholderConfiguration {

@Value("${system.name}")
private String systemName;
}
utils:properties方式
  1. XML配置application-utils-property.xml

    1
    <utils:properties id="system" location="classpath:system.properties" />
  2. 配置类UtilsPropertyConfiguration

    1
    2
    3
    4
    5
    6
    7
    8
    9
    @Setter
    @Getter
    @Component
    @ImportResource("classpath:/application-utils-property.xml")
    public class UtilsPropertyConfiguration {

    @Value("#{system['system.name']}")
    public String systemName;
    }

@Value表达式详见 Spring Expression Language (SpEL)

Spring 注解方式

@PropertySource注解

1
2
3
4
5
6
7
8
9
@Setter
@Getter
@Component
@PropertySource(value = "classpath:/system.properties")
public class PropertySourceConfiguration {

@Value("${system.name}")
private String systemName;
}

Spring Boot 注解方式

@ConfigurationProperties

启用方式

@Compnent
@EnableConfigurationProperties

问题

若property文件中有中文,代码中获取会出现乱码

答:Spring XML 三种方式分别解决如下:

  • property-placeholder方式可利用属性file-encoding配置文件编码
  • PropertyPlaceholderConfigurer方式可利用property属性fileEncoding配置文件编码
  • utils:properties方式可利用将中文转换为Unicode编码写在properties文件中

Spring 注解方式可利用@PropertySource注解属性encoding配置文件编码

Spring XML中@Value表达式中$与#的区别

答:@Value中使用的是Spring Expression Language (SpEL)的语法,具体可查看官网介绍。$是引用配置文件中属性名称;#是引用Bean中的属性或者计算表达式,属性可用.进行链接获取,若Bean的属性中也有.,需要采用Bean['X.Y']这种写法


SpringBoot自动装配
http://example.com/2019/05/10/SpringBoot/SpringBoot自动装配/
作者
FelixFly
发布于
2019年5月10日
许可协议