springboot(⼗三)常⽤的接⼝,⼯具类,注解汇总
1.springboot 常⽤接⼝
1.1 Aware接⼝
Spring IOC容器中 Bean是感知不到容器的存在,Aware(意识到的)接⼝就是帮助Bean感知到IOC容器的存在,即获取当前Bean对应的Spring的⼀些组件,如当前Bean对应的ApplicationContext等。
1.1.1 ApplicationContextAware 获取ApplicationContext
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public SpringContextUtil() {
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static <T> T getBean(String name) throws BeansException {
Bean(name);
}
public static <T> T getBean(Class<?> clz) throws BeansException {
Bean(clz);
}
}
1.1.2 EnvironmentAware 环境变量读取和属性对象获取
关于Enviroment作⽤:
Environment:环境,Profile 和 PropertyResolver 的组合。
Environment 对象的作⽤是确定哪些配置⽂件(如果有)当前处于活动状态,以及默认情况下哪些配置⽂件(如果有)应处于活动状态。
properties 在⼏乎所有应⽤程序中都发挥着重要作⽤,并且有多种来源:属性⽂件,JVM 系统属性,系统环境变量,JNDI,
servlet 上下⽂参数,ad-hoc 属性对象,映射等。同时它继承 PropertyResolver 接⼝,
所以与属性相关的 Environment 对象其主要是为⽤于配置属性源和从中属性源中解析属性。
@Component
public class MyEnvironment implements EnvironmentAware {
private Environment environment;
@Override
public void setEnvironment(Environment environment) {
}
}
Aware的其他⼦接⼝
ApplicationEventPublisherAware (t):事件发布
⽤法可参考:
ServletContextAware (org.t): ServletContext
ServletConfigAware (org.t): ServletConfig
⽤法可参考:
MessageSourceAware (t): 国际化
⽤法可参考:
ResourceLoaderAware (t):访问底层资源的加载器
⽤法参考:
NotificationPublisherAware (org.ification):JMX通知
Spring JMX之⼀:使⽤JMX管理Spring Bean:
Spring JMX之三:通知的处理及监听:
BeanFactoryAware (org.springframework.beans.factory): 申明BeanFactory
Spring BeanFactory体系:
EmbeddedValueResolverAware (t): ⼿动读取配置
使⽤⽅式可以参考:
ImportAware (t.annotation):处理⾃定义注解
关于ImportAware的作⽤可以看:
BootstrapContextAware (org.t): 资源适配器BootstrapContext,如JAC,CCI
springcloud情操陶冶-bootstrapContext(⼆):
LoadTimeWeaverAware (t.weaving):加载Spring Bean时植⼊第三⽅模块,如AspectJ
说说在 Spring AOP 中如何实现类加载期织⼊(LTW):
BeanClassLoaderAware (org.springframework.beans.factory): 加载Spring Bean的类加载器
深⼊理解Java类加载器(ClassLoader):
BeanNameAware (org.springframework.beans.factory): 申明Spring Bean的名字
ApplicationContextAware (t):申明ApplicationContext
1.2 ApplicationEvent ApplicationListener ⾃定义事件,及监听
如果容器中存在ApplicationListener的Bean,当ApplicationContext调⽤publishEvent⽅法时,对应的Bean会被触发。
spring内置事件
内置事件描述ContextRefreshedEvent
ApplicationContext 被初始化或刷新时,该事件被触发。这也可以在ConfigurableApplicationContext 接⼝中使⽤ refresh() ⽅法来发⽣。此处的初始化是指:所有的Bean 被成功装载,后处理Bean 被检测并激活,所有Singleton Bean 被预实例
化,ApplicationContext 容器已就绪可⽤
ContextStartedEvent
当使⽤ ConfigurableApplicationContext (ApplicationContext ⼦接⼝)接⼝中的 start() ⽅法启动ApplicationContext 时,该事件被发布。你可以调查你的数据库,或者你可以在接受到这个事件后springcloud和springboot
重启任何停⽌的应⽤程序。
ContextStoppedEvent
当使⽤ ConfigurableApplicationContext 接⼝中的 stop() 停⽌ ApplicationContext 时,发布这个事件。你可以在接受到这个事件后做必要的清理的⼯作。
ContextClosedEvent
当使⽤ ConfigurableApplicationContext 接⼝中的 close() ⽅法关闭 ApplicationContext 时,该事件被发布。⼀个已关闭的上下⽂到达⽣命周期末端;它不能被刷新或重启。
RequestHandledEvent
这是⼀个 web-specific 事件,告诉所有 bean HTTP 请求已经被服务。只能应⽤于使⽤DispatcherServlet 的Web 应⽤。在使⽤Spring 作为前端的MVC 控制器时,当Spring 处理⽤户请求结
束后,系统会⾃动触发该事件。
同样事件可以⾃定义、监听也可以⾃定义
@Compone
public
@Overrid            System
}
}
1.3 InitializingBean 接⼝
InitializingBean 为bean 提供了初始化⽅法的⽅式,它只包括afterPropertiesSet ⽅法,凡是实现该接⼝的类,在初始化bean 的时候会执⾏该⽅法。效果等同于bean 的init-method 属性的使⽤或者@PostContsuct 注解的使⽤。
三种⽅式的执⾏顺序:@PostContsuct -> 执⾏InitializingBean 接⼝中定义的⽅法 -> 执⾏init-method 属性指定的⽅法。
@Component
public  class  TestInitializingBean implements  InitializingBean{
@Override
public  void  afterPropertiesSet() throws  Exception {
//bean 初始化后执⾏
}
}
1.4 BeanPostProcessor 接⼝
实现BeanPostProcessor 接⼝的类即为Bean 后置处理器,Spring 加载机制会在所有Bean 初始化的时候遍历调⽤每个Bean 后置处理器。BeanPostProcessor 为每个bean 实例化时提供个性化的修改,做些包装等。
其顺序为:Bean 实例化 -> 依赖注⼊ -> Bean 后置处理器 (postProcessBeforeInitialization)  -> @PostConstruct  ->  InitializingBean 实现类 -> 执⾏init-method 属性指定的⽅法 -> Bean 后置处理器 (postProcessAfterInitialization)
public  class  MyBeanPostProcessor implements  BeanPostProcessor {
/**
* 在bean 实例化之前回调
*/
public Object postProcessBeforeInitialization(Object bean, String beanName)throws BeansException {
System.out.println("postProcessBeforeInitialization: " + beanName);
return bean;
}
/**
* 在bean实例化之后回调
*/
public Object postProcessAfterInitialization(Object bean, String beanName)throws BeansException {
System.out.println("postProcessAfterInitialization: " + beanName);
return bean;
}
}
⽤法可以参考:
1.5 BeanFactoryPostProcessor接⼝
bean⼯⼚的bean属性处理容器,说通俗⼀些就是可以管理我们的bean⼯⼚内所有的beandefinition(未实例化)数据,可以随⼼所欲的修改属性@Component
@Slf4j
public class BrianBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
  public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    BeanDefinition bd = BeanDefinition("brianBean");
    MutablePropertyValues pv = bd.getPropertyValues();
    if (pv.contains("kawa")) {
      pv.addPropertyValue("kawa", "修改属性kawa的值");
    }
    }
  }
⽤法可以参考:
1.6 CommandLineRunner 和 ApplicationRunner接⼝
CommandLineRunner 及 ApplicationRunner 都可实现在项⽬启动后执⾏操作别ApplicationRunner会封装命令⾏参数,可以很⽅便地获取到命令⾏参数和参数值
@Component
@Slf4j
@Order(value = 2)
public class InitServiceConfiguration implements CommandLineRunner {
@Autowired
private ApplicationContext applicationContext;
@Override
public void args) throws Exception {
Map<String, AbstractInitService> serviceMap = BeansOfType(AbstractInitService.class);
if (serviceMap == null) {
return;
}
ExecutorService fixedThreadPool = wFixedThreadPool(3);
for (Map.Entry<String, AbstractInitService> entry : Set()) {
log.info("初始化:{}", Key());
}
fixedThreadPool.shutdown();
}
}
⽤法可参考:
2.springBoot 常⽤⼯具类
此处的汇总也包含spring常⽤的⼯具类
2.1 字符串⼯具类 org.springframework.util.StringUtils
⾸字母⼤写:public static String capitalize(String str)
⾸字母⼩写:public static String uncapitalize(String str)
判断字符串是否为null或empty:public static boolean hasLength(String str)
判断字符串是否为⾮空⽩字符串(即⾄少包含⼀个⾮空格的字符串):public static boolean hasText(String str)
获取⽂件名:public static String getFilename(String path) 如e.g. "" -> ""
获取⽂件扩展名:public static String getFilenameExtension(String path) 如"" -> "txt"
还有譬如数组转集合、集合转数组、路径处理、字符串分离成数组、数组或集合合并为字符串、数组合并、向数组添加元素等。
2.2 对象序列化⼯具类 org.springframework.util.SerializationUtils
public static byte[] serialize(Object object)
public static Object deserialize(byte[] bytes)
2.3 数字处理⼯具类 org.springframework.util.NumberUtils
字符串转换为Number并格式化,包括具体的Number实现类,如Long、Integer、Double,字符串⽀持16进制字符串,并且会⾃动去除字符串中的空格:
public static <T extends Number> T parseNumber(String text, Class<T> targetClass)
public static <T extends Number> T parseNumber(String text, Class<T> targetClass, NumberFormatnumberFormat)
各种Number中的转换,如Long专为Integer,⾃动处理数字溢出(抛出异常):
public static <T extends Number> T convertNumberToTargetClass(Number number, Class<T> targetClass)
2.4 ⽂件复制⼯具类 org.springframework.util.FileCopyUtils
流与流之间、流到字符串、字节数组到流等的复制
2.5 ⽬录复制⼯具类 org.springframework.util.FileSystemUtils
递归复制、删除⼀个⽬录
2.6 MD5加密⼯具类org.springframework.util.DigestUtils
字节数组的MD5加密public static String md5DigestAsHex(byte[] bytes)
2.7 ResourceUtils
org.l.ResourceUtils ⽤于处理表达资源字符串前缀描述资源的⼯具. 如: "classpath:".有 getURL, getFile, isFileURL, isJarURL, extractJarFileURL
2.8 annotation.AnnotationUtils 处理注解
Spring:AnnotationUtils⼯具类与注解参数说明:
2.9 io.support.PropertiesLoaderUtils 加载Properties资源⼯具类,和Resource结合
Spring⼯具类之PropertiesLoaderUtils:
2.10 org.t.properties.bind.Binder
Springboot 2.x新引⼊的类,负责处理对象与多个ConfigurationPropertySource(属性)之间的绑定。⽐Environment类好⽤很多,可以⾮常⽅便地进⾏类型转换,以及提供回调⽅法介⼊绑定的各个阶段进⾏深度定制Spring Boot中的属性绑定的实现
2.11 NestedExceptionUtils
2.12 xml⼯具类
org.l.AbstractStaxContentHandler
org.l.AbstractStaxXMLReader
org.l.AbstractXMLReader
org.l.AbstractXMLStreamReader
org.l.DomUtils
org.l.StaxUtils
org.l.TransformerUtils
2.13 web⼯具类
org.springframework.web.util.CookieGenerator
org.springframework.web.util.HtmlCharacterEntityDecoder
org.springframework.web.util.HtmlCharacterEntityReferences
org.springframework.web.util.HtmlUtils
org.springframework.web.util.JavaScriptUtils
[Java⼯具类]spring常⽤⼯具类 2.特殊字符转义和⽅法⼊参检测⼯具类:
org.springframework.web.util.HttpUrlTemplate  这个类⽤于⽤字符串模板构建url, 它会⾃动处理url⾥的汉字及其它相关的编码. 在读取别⼈提供的url资源时, 应该经常⽤
org.springframework.web.util.Log4jConfigListener  ⽤listener的⽅式来配制log4j在web环境下的初始化
org.springframework.web.util.UriTemplate
org.springframework.web.util.UriUtils  处理uri⾥特殊字符的编码
org.springframework.web.util.WebUtils
org.springframework.web.bind.ServletRequestUtils
介绍Spring WebUtils 和 ServletRequestUtils:
2.14 其它⼯具集
org.springframework.util.AntPathMatcher  ant风格的处理(uri路径匹配使⽤较多)
org.springframework.util.AntPathStringMatcher
详情参考:
org.springframework.util.Assert    断⾔⼯具类(经常⽤到)
详情参考:
org.springframework.util.ClassUtils  Class的处理(isPresnt()⽅法经常⽤到)
详情参考:
org.springframework.util.CollectionUtils  集合的⼯具(不⽤多介绍了)
org.springframework.util.CommonsLogWriter (不常⽤到)
⽤例参考:
org.springframework.util.CompositeIterator (复合的Iterator)
⽤法根简单,看下源码就知道它的⽤法
org.springframework.util.ConcurrencyThrottleSupport (控制线程数量)
详情参考:
org.springframework.util.CustomizableThreadCreator (⾃定义Thread组)
org.springframework.util.LinkedCaseInsensitiveMap key值不区分⼤⼩写的LinkedMap
org.springframework.util.LinkedMultiValueMap  ⼀个key可以存放多个值的LinkedMap
org.springframework.util.Log4jConfigurer  ⼀个log4j的启动加载指定配制⽂件的⼯具类
org.springframework.util.ObjectUtils  有很多处理null object的⽅法. 如nullSafeHashCode, nullSafeEquals, isArray, containsElement, addObjectToArray, 等有⽤的⽅法
org.springframework.util.PatternMatchUtils  spring⾥⽤于处理简单的匹配. 如 Spring's typical "xxx", "xxx" and "xxx" pattern styles
org.springframework.util.PropertyPlaceholderHelper  ⽤于处理占位符的替换
org.springframework.util.ReflectionUtils  反映常⽤⼯具⽅法. 有 findField, setField, getField, findMethod, invokeMethod等有⽤的⽅法
org.springframework.util.StopWatch  ⼀个很好的⽤于记录执⾏时间的⼯具类, 且可以⽤于任务分阶段的测试时间. 最后⽀持⼀个很好看的打印格式. 这个类应该经常⽤
org.springframework.util.SystemPropertyUtils
org.springframework.util.TypeUtils  ⽤于类型相容的判断. isAssignable
org.springframework.util.WeakReferenceMonitor  弱引⽤的监控
java.util.Properties 加载⽂件资源
详细参考:
spring好⽤的的⼯具类集中在org.springframework.util这个包下,没事可以多翻⼀翻,下⾯也是别⼈总结的⼯具类可以看⼀看
3.springBoot 常⽤注解
3.1 spirngboot常⽤注解
@Component可配合CommandLineRunner使⽤,在程序启动后执⾏⼀些基础任务。
@JsonBackReference解决嵌套外链问题。
解决Json ⽆线递归问题注解@JsonBackReference该注解加在GET SET⽅法头上:
@RepositoryRestResourcepublic配合spring-boot-starter-data-rest使⽤。
@EnableAutoConfiguration:Spring Boot⾃动配置(auto-configuration):尝试根据你添加的jar依赖⾃动配置你的Spring应⽤。
例如,如果你的classpath下存在HSQLDB,并且你没有⼿动配置任何数据库连接beans,那么我们将⾃动配置⼀个内存型(in-memory)数据库,
你可以将@EnableAutoConfiguration或者@SpringBootApplication注解添加到⼀个@Configuration类上来选择⾃动配置。
如果发现应⽤了你不想要的特定⾃动配置类,你可以使⽤@EnableAutoConfiguration注解的排除属性来禁⽤它们。
@ComponentScan:表⽰将该类⾃动发现扫描组件。个⼈理解相当于,如果扫描到有@Component、@Controller、@Service等这些注解的类,
并注册为Bean,可以⾃动收集所有的Spring组件,包括@Configuration类。我们经常使⽤@ComponentScan注解搜索beans,并结合@Autowired注解导⼊。
可以⾃动收集所有的Spring组件,包括@Configuration类。我们经常使⽤@ComponentScan注解搜索beans,并结合@Autowired注解导⼊。
如果没有配置的话,Spring Boot会扫描启动类所在包下以及⼦包下的使⽤了@Service,@Repository等注解的类。
@Import:⽤来导⼊其他配置类。
@ImportResource:⽤来加载xml配置⽂件。
@Inject:等价于默认的@Autowired,只是没有required属性;
@Qualifier:当有多个同⼀类型的Bean时,可以⽤@Qualifier(“name”)来指定。与@Autowired配合使⽤。@Qualifier限定描述符除了能根据名字进⾏注⼊,但能进⾏更细粒度的控制如何选择候选者,具体使⽤⽅式如下:@Autowired
@Qualifier(value = “demoInfoService”)
private DemoInfoService demoInfoService;
@Resource(name=”name”,type=”type”):没有括号内内容的话,默认byName。与@Autowired⼲类似的事。
3.2 JPA注解
@Entity:@Table(name=”“):表明这是⼀个实体类。⼀般⽤于jpa这两个注解⼀般⼀块使⽤,但是如果表名和实体类名相同的话,@Table可以省略
@MappedSuperClass:⽤在确定是⽗类的entity上。⽗类的属性⼦类可以继承。
@NoRepositoryBean:⼀般⽤作⽗类的repository,有这个注解,spring不会去实例化该repository。
@Column:如果字段名与列名相同,则可以省略。
@Id:表⽰该属性为主键。
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = “repair_seq”):
表⽰主键⽣成策略是sequence(可以为Auto、IDENTITY、native等,Auto表⽰可在多个数据库间切换),指定sequence的名字是repair_seq。
@SequenceGeneretor(name = “repair_seq”, sequenceName = “seq_repair”, allocationSize = 1):
name为sequence的名称,以便使⽤,sequenceName为数据库的sequence名称,两个名称可以⼀致。
@Transient:表⽰该属性并⾮⼀个到数据库表的字段的映射,ORM框架将忽略该属性。如果⼀个属性并⾮数据库表的字段映射,
就务必将其标⽰为@Transient,否则,ORM框架默认其注解为@Basic。@Basic(fetch=FetchType.LAZY):标记可以指定实体属性的加载⽅式
@JsonIgnore:作⽤是json序列化时将Java bean中的⼀些属性忽略掉,序列化和反序列化都受影响。
@JoinColumn(name=”loginId”):⼀对⼀:本表中指向另⼀个表的外键。⼀对多:另⼀个表指向本表的外键。
@OneToOne、@OneToMany、@ManyToOne:对应hibernate配置⽂件中的⼀对⼀,⼀对多,多对⼀。
3.3 springMVC相关注解
@RequestMapping:@RequestMapping(“/path”)表⽰该控制器处理所有“/path”的UR L请求。RequestMapping是⼀个⽤来处理请求地址映射的注解,可⽤于类或⽅法上。
⽤于类上,表⽰类中的所有响应请求的⽅法都是以该地址作为⽗路径。
该注解有六个属性:
params:指定request中必须包含某些参数值是,才让该⽅法处理。
headers:指定request中必须包含某些指定的header值,才能让该⽅法处理请求。
value:指定请求的实际地址,指定的地址可以是URI Template 模式
method:指定请求的method类型, GET、POST、PUT、DELETE等
consumes:指定处理请求的提交内容类型(Content-Type),如application/json,text/html;

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。