关于springboot读取自定义的配置

我是自定义一个关于发邮件的自定义文件,然后读取它,在网上找了很多关于读取文件的,结果一直发现值为null,用@Value读取也为null,因为我不是在controller层读取配置,而是在util工具包读取,就十分麻烦,

记录下来自己走过的坑:

第一步不用说,创建配置文件;

第二步,创建配置文件的类:

@Component
@Configuration
@ConfigurationProperties(prefix = "email", ignoreUnknownFields = false)
@PropertySource(value={"classpath:email.properties"},encoding="utf-8")
public class EmailProperty {
	
	private String from;
	private String clientPassWord;
	private String port;
	private String ipAddress;
	private String server;
    
        /**
        * 此处省略getter和setter方法
        */
}

第三步,在自己需要使用的地方,注:(非controller层)

@Component // 很重要
public class EmailUtils {

    @Autowired // 非常重要
    private EmailProperty em;
	
    public static EmailUtils email; // 也重要
	
    @PostConstruct // 极其重要
    public void init() {
	email = this;
	email.em = this.em;
    }

    // 下面就是调用了,
    .......
    email.em.getFrom()  //就获得想要的值,非null
    .......
	
}

三步解决,非controller层,读取配置文件

猜你喜欢

转载自blog.csdn.net/ademing/article/details/81667322