@ConfigurationProperties注解的使用

定义

该注解将外部配置文件(比如applicaition.properties、application.yml)加载进来,填充对象的对应字段的数据,然后供其他Bean使用。

注意

需要setter方法将文件中的值写入到对象属性中,如果没有setter需要写入的属性值为null

例子

bootstrap.yml

jpush:
  appKey: 3def5e50578d10c213173678
  masterSecret: 9067bc19e4dbccd1a7f8d8f8
JiGuangConfig(极光推送)
package config.jpush;

import cn.jpush.api.JPushClient;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * @author yjw
 * @date 2020/6/9
 */
@Setter
@Configuration
@ConfigurationProperties(prefix = "jpush")
public class JiGuangConfig {

    private String appKey;

    private String masterSecret;

    private JPushClient jPushClient;

    /**
     * 初始化JPushClient
     */
    @PostConstruct
    private void initJPushClient() {
        jPushClient = new JPushClient(masterSecret, appKey);
    }

    /**
     * 获取JPushClient
     *
     * @return JPushClient
     */
    public JPushClient getJPushClient() {
        return jPushClient;
    }
}

如果用@Value也可以实现

package com.cdls.carp.business.config.jpush;

import cn.jpush.api.JPushClient;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * @author yjw
 * @date 2020/6/9
 */
//@Setter
@Configuration
//@ConfigurationProperties(prefix = "jpush")
public class JiGuangConfig {

    @Value("${jpush.appKey}")
    private String appKey;

    @Value("${jpush.masterSecret}")
    private String masterSecret;

    private JPushClient jPushClient;

    /**
     * 初始化JPushClient
     */
    @PostConstruct
    private void initJPushClient() {
        jPushClient = new JPushClient(masterSecret, appKey);
    }

    /**
     * 获取JPushClient
     *
     * @return JPushClient
     */
    public JPushClient getJPushClient() {
        return jPushClient;
    }
}

 

你可能感兴趣的:(@ConfigurationProperties注解的使用)