记录工作中见到的注解,共同学习,一起进步,如有错误,欢迎指正,欢迎补充!
1. @Conditional
@Conditional是Spring4新提供的注解,它的作用是按照一定的条件进行判断,满足条件给容器注册bean。
@Conditional的定义:
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Conditional {
Class extends Condition>[] value();
}
从代码中可以看到,需要传入一个Class数组,并且需要继承Condition接口:
public interface Condition {
boolean matches(ConditionContext var1, AnnotatedTypeMetadata var2);
}
Condition是个接口,需要实现matches方法,返回true则注入bean,false则不注入。
具体用法请参考示例:文章链接
派生
@ConditionalOnMissingBean(HttpUtils.class)
当缺少某个Bean时注入。
2.@Scope("prototype")
- singleton 表示在spring容器中的单例,通过spring容器获得该bean时总是返回唯一的实例
- prototype表示每次获得bean都会生成一个新的对象
- request表示在一次http请求内有效(只适用于web应用)
- session表示在一个用户会话内有效(只适用于web应用)
- globalSession表示在全局会话内有效(只适用于web应用)
3.@Configurable
用来自动注入bean的注解,不需要通过BeanFactory去获取
示例
定义了一个httpclient的工具类:
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Component
public class HttpUtils {
@Autowired
private CloseableHttpClient httpClient;
public String doGet(String url) {
String respStr = this.doGet(url, null);
return respStr;
}
public String doGet(String url, Map headerMap) {
HttpGet get = new HttpGet(url);
if (headerMap != null && headerMap.size() > 0) {
headerMap.forEach((k, v) -> {
get.setHeader(k, v);
});
}
String respStr = this.doHttp(get);
return respStr;
}
public String doPostForm(String url, Map data) {
String respStr = this.doPostForm(url, null, data);
return respStr;
}
public String doPostForm(String url, Map header, Map data) {
HttpPost post = new HttpPost(url);
if (header != null) {
header.forEach((name, value) -> post.addHeader(name, value));
}
List pairList = new ArrayList<>(data.size());
for (Map.Entry entry : data.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
pairList.add(pair);
}
UrlEncodedFormEntity entity = null;
try {
entity = new UrlEncodedFormEntity(pairList, "UTF-8");
} catch (UnsupportedEncodingException e) {
}
post.setEntity(entity);
String respStr = this.doHttp(post);
return respStr;
}
public String doPostJson(String url, T data) {
String respStr = this.doPostJson(url, null, data);
return respStr;
}
public String doPostJson(String url, Map header, T data) {
ContentType contentType = ContentType.APPLICATION_JSON;
String respStr = this.doPostJson(url, contentType, header, data);
return respStr;
}
public String doPostJson(String url, ContentType contentType, Map header, T data) {
HttpPost post = new HttpPost(url);
if (header != null) {
header.forEach((name, value) -> post.addHeader(name, value));
}
if (contentType == null) {
contentType = ContentType.APPLICATION_JSON;
}
String jsonString = JsonUtils.beanToJson(data);
StringEntity entity = new StringEntity(jsonString, contentType);
post.setEntity(entity);
String respStr = this.doHttp(post);
return respStr;
}
/**
* 下载文件。
*
* @param url 下载地址
* @param savePath 保存的物理路径
* @param fileName 保存的文件名。
* @return 下载成功,还是失败。
*/
public boolean download(String url, String savePath, String fileName) {
String saveFileName = this.doDownload(url, savePath, fileName);
File file = new File(saveFileName);
if (!file.exists()) {
return false;
}
return FileUtils.sizeOf(file) > 0;
}
private String doHttp(HttpUriRequest request) {
String respStr = null;
// 发起请求
CloseableHttpResponse response = null;
try {
response = this.httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
respStr = EntityUtils.toString(responseEntity);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
}
}
}
return respStr;
}
private String doDownload(String url, String savePath, String fileName) {
Assert.isNull(savePath, "HTTP下载的存储路径不能为空!");
String saveFileName = null;
String respStr = null;
// 发起请求
CloseableHttpResponse response = null;
try {
//文件保存位置
File saveDir = new File(savePath);
if (!saveDir.exists()) {
saveDir.mkdirs();
}
saveFileName = saveDir + File.separator + fileName;
File file = new File(saveFileName);
if (!file.getParentFile().exists()) {
file.mkdirs();
}
FileOutputStream fos = new FileOutputStream(file);
HttpGet request = new HttpGet(url);
response = this.httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
InputStream content = responseEntity.getContent();
StreamUtils.copy(content, fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
}
}
}
return saveFileName;
}
}
配置类:
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
@Configurable
public class AppConfig {
@ConditionalOnMissingBean(HttpUtils.class)
@Bean
public HttpUtils getHttpUtils() {
return new HttpUtils();
}
}
使用:
public abstract class BaseServiceImpl implements BaseService {
private HttpUtils httpUtils;
public BaseServiceImpl(HttpUtils httpUtils) {
this.httpUtils = httpUtils;
}
}
public class aServiceImpl extends BaseServiceImpl {
@Autowired
public aServiceImpl (HttpUtils httpUtils) {
super(httpUtils);
}
}
当找不到HttpUtils时,会自动注入。