springboot将配置文件(.yml、.properties)的值注入到类属性中

 方式一:

1、关键注解:@Component、@Value

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Data
@Component //将该类作为一个组件
public class TestUtil {
    
    @Value("${my.authz-code}")  //属性值设置
    private String authzCode;
    
    @Value("${my.from}")
    private String from;
    
    @Value("${my.host}")
    private String host;

}

2、在yml或properties文件中进行配置

my:
  #属性1
  authz-code: qweqwe
  #属性2
  from: [email protected]
  #属性3
  host: smtp.qq.com

注:

方式二: 

1、关键注解: @ConfigurationProperties(prefix = "youPrefix")、@Component

2、yml相应配置

猜你喜欢

转载自blog.csdn.net/weixin_44351477/article/details/108253085