注入任何类
本节通过一个实际的例子来讲解如何注入一个普通类,并且说明这样做的好处。
假设一个需求是这样的:项目要求使用阿里云的 OSS 进行文件上传。
我们知道,一个项目一般会分为开发环境、测试环境和生产环境。OSS 文件上传一般有如下几个参数:appKey、appSecret、bucket、endpoint 等。不同环境的参数都可能不一样,这样便于区分。按照传统的做法,我们在代码里设置这些参数,这样做的话,每次发布不同的环境包都需要手动修改代码。
这个时候,我们就可以考虑将这些参数定义到配置文件里面,通过前面提到的 @Value 注解取出来,再通过 @Bean 将其定义为一个 Bean,这时我们只需要在需要使用的地方注入该 Bean 即可。
首先在 application.yml 加入如下内容:
appKey: 1
appSecret: 1
bucket: lynn
endPoint: https://www.aliyun.com
其次创建一个普通类:
public class Aliyun {
private String appKey;
private String appSecret;
private String bucket;
private String endPoint;
public static class Builder{
private String appKey;
private String appSecret;
private String bucket;
private String endPoint;
public Builder setAppKey(String appKey){
this.appKey = appKey;
return this;
}
public Builder setAppSecret(String appSecret){
this.appSecret = appSecret;
return this;
}
public Builder setBucket(String bucket){
this.bucket = bucket;
return this;
}
public Builder setEndPoint(String endPoint){
this.endPoint = endPoint;
return this;
}
public Aliyun build()