Spring Boot实录笔记

1: Spring IoC?
在Spring中把每一个需要管理的对象称为Spring Bean, 而Spring管理这些Bean的容器, 被我们称为Spring IoC容器, IoC容器需要具备两个基本功能:
1:通过描述管理Bean, 包含发布和获取Bean
2:通过描述完成Bean之间的依赖关系
2:Spring AOP?
3:@Value
使用 . . . 这 样 的 占 位 符 读 取 配 置 在 属 性 文 件 中 的 内 容 , 默 认 属 性 文 件 ( a p p l i c a t i o n . p r o p e r t i e s ) , 如 果 需 要 指 定 文 件 可 以 使 用 @ P r o p e r t y S o u r c e e g : @ P r o p e r t y S o u r c e ( v a l u e = " c l a s s p a t h : / c o n f / i n s t a l l a t i o n . p r o p e r t i e s " , i g n o r e R e s o u r c e N o t F o u n d = t r u e ) @ V a l u e ( " {...}这样的占位符读取配置在属性文件中的内容,默认属性文件(application.properties), 如果需要指定文件可以使用@PropertySource eg:@PropertySource(value = "classpath:/conf/installation.properties", ignoreResourceNotFound=true) @Value(" ...,(application.properties),使@PropertySourceeg:@PropertySource(value="classpath:/conf/installation.properties",ignoreResourceNotFound=true)@Value("{database.username}")
value可以配置多个配置文件, 使用classpath前缀, 意味着去类文件路径下找到属性文件, ignoreResourceNotFound默认为false, 找不到就抛异常, 如果未true则不会抛异常.
4:@Profile 与 @ActiveProfiles
https://blog.csdn.net/wild46cat/article/details/71189858?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase
参考这个博客, 可以指定Bean状态的类别, 根据@Profile的申明多少Bean, @ActiveProfiles在调用的时候声明使用哪类Bean
5@Value("#{…}"), #{}它将具有运算的功能,比如:
@Value("#{1+2}")
private int num;
@Value("#{beanName.str}")
private String strVaule;

6:AOP?

只要按照一定的规则, 我就可以将你的代码植入事先约定的流程中, 实际上AOP也是一种约定流程的编程. *Spring AOP只能对方法进行拦截.*

7:@Transactional?
表明该方法需要事务运行, 没有任何数据库打开和关闭的代码, 也没有事务回滚和提交的代码, 却实现了数据库的打开和关闭, 事务的回滚及提交.
eg:
@Transactional(propagation = Propagation.REQUIRED)
public void deleteDataDstBatch(List indexCodes) {
deleteDstsAction(indexCodes); //直接执行删除数据的操作.
}
8:@Aspect
AOP中切面声明, 当以该注解时, Spring就知道这是一个切面. 配合使用还有 @Before @After @AfterReturning @AfterThrowing @Around等.
9:@DeclareParents 引入新的类来增强服务, 它有两属性必须配置, value, defaultImpl

10@SpringBootApplication(scanBasePackages = {“com.hikvision”})
@SpringBootApplication(scanBasePackages = {“com.hikvision”})
@EnableAspectJAutoProxy
定义扫描包
11:当存在多个切面时, 使用@Order指定切面执行顺序.
@Aspect
@Order(1)
12:创建指定的编码格式的字符
public static final Charset DEFAULT_CHARSET = Charset.forName(“UTF-8”);
定义 Charset的默认Unicode编码(DEFAULT_CHARSET)是UTF-8
13:@EnableCaching //https://segmentfault.com/a/1190000011069802
@EnableCaching注解是spring framework中的注解驱动的缓存管理功能。自spring版本3.1起加入了该注解。如果你使用了这个注解,那么你就不需要在XML文件中配置cache manager了。

当你在配置类(@Configuration)上使用@EnableCaching注解时,会触发一个post processor,这会扫描每一个spring bean,查看是否已经存在注解对应的缓存。如果找到了,就会自动创建一个代理拦截方法调用,使用缓存的bean执行处理。

14:如下代码, 这里errorHandler接口中实现了CacheErrorHandler的所有方法, 返回这个已经实现的接口的cacheErrorHandler对象.
/**
* redis数据操作异常处理 这里的处理:在日志中打印出错误信息,但是放行
* 保证redis服务器出现连接等问题的时候不影响程序的正常运行,使得能够出问题时不用缓存
* @return
*/
@Bean
@Override
public CacheErrorHandler errorHandler() {
CacheErrorHandler cacheErrorHandler = new CacheErrorHandler() {
@Override
public void handleCacheGetError(RuntimeException e, Cache cache, Object key) {
logger.error(HikLog.toLog(ErrorCode.REDIS_ERROR.getErrorCode(), “redis error: key:{}”), key, e);
}

		@Override
		public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) {
			logger.error(HikLog.toLog(ErrorCode.REDIS_ERROR.getErrorCode(), "redis error: key:{}"), key, e);
		}

		@Override
		public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) {
			logger.error(HikLog.toLog(ErrorCode.REDIS_ERROR.getErrorCode(), "redis error: key:{}"), key, e);
		}

		@Override
		public void handleCacheClearError(RuntimeException e, Cache cache) {
			logger.error(HikLog.toLog(ErrorCode.REDIS_ERROR.getErrorCode(), "redis error"), e);
		}
	};
	return cacheErrorHandler;
}

15:自定义注解

1:定义自定义注解类
	@Target({ **ElementType.METHOD**})
	@Retention(**RetentionPolicy.RUNTIME**)
	public **@interface** TraceLog{
		String value() default "";
	}
2:定义申明切面类(@Aspect), 确定切点(Pointcut), 及定义增强(@Before @After @AfterReturning @AfterThrowing @Around等)注解方法
		例子:
				@Component
				@Aspect
				public class LogAspect {
						//@Pointcut声明了切点(这里的切点是我们自定义的注解类)
						 @Pointcut("@annotation(com.up.springboot.anno.*TraceLog*)")
						 private void pointcut() {}
						 //前置增强,目标方法执行之前执行
						 @Before(value = "pointCut()")
						public void beforeFunc(JoinPoint joinPoint){
						}
						/**
 						* 环绕通知:
				 		*   注意:Spring AOP的环绕通知会影响到AfterThrowing通知的运行,不要同时使用
				 		 *
 						*   环绕通知非常强大,可以决定目标方法是否执行,什么时候执行,执行时是否需要替换方法参数,执行完毕是否需要替换返回值。
 						*   环绕通知第一个参数必须是org.aspectj.lang.ProceedingJoinPoint类型
						 //环绕增强,目标方法执行前后分别执行一些代码
						 @Around(value = "pointCut()")
						public void aroundFunc(JoinPoint joinPoint){
						}
						 /**
					 * 后置返回
				     *      如果第一个参数为JoinPoint,则第二个参数为返回值的信息
					 *      如果第一个参数不为JoinPoint,则第一个参数为returning中对应的参数
				   * returning:限定了只有目标方法返回值与通知方法参数类型匹配时才能执行后置返回通知,否则不执行,
 				*            参数为Object类型将匹配任何目标返回值
 				*/
				 	 @AfterReturning(value = POINT_CUT,returning = "result")
						public void afterReturningFunc(JoinPoint joinPoint){
						}
						/**
 					* 后置异常通知
 					*  定义一个名字,该名字用于匹配通知实现方法的一个参数名,当目标方法抛出异常返回后,将把目标方法抛出的异常传给通知方法;
					 *  throwing:限定了只有目标方法抛出的异常与通知方法相应参数异常类型时才能执行后置异常通知,否则不执行,
 					*  对于throwing对应的通知方法参数为Throwable类型将匹配任何异常。
				 * @param joinPoint
			 * @param exception
			    */
					//异常抛出增强,目标方法发生异常的时候执行
						 @AfterThrowing(value = "pointCut()", throwing = "exception")
						public void afterTrowingFunc(JoinPoint joinPoint){
						}
						 //后置增强,不管是抛出异常或者正常退出都会执行
						 @After(value = "pointCut()")
						public void afterFunc(JoinPoint joinPoint){
						}

				}

3:使用注解
@RequestMapping("/pernas/test")
public class TestController {
 @SuppressWarnings("finally")
 @TraceLog()
 @GetMapping("/test")
 public void procTest()
 {
 }
 }
 参考资料地址:
 https://zhuanlan.zhihu.com/p/96597358
 https://blog.csdn.net/qmqm011/article/details/90172698

16:@ConditionalOnProperty

  这个注解能够控制某个configuration是否生效。具体操作是通过其两个属性name以及havingValue来实现的,其中name用来从application.properties中读取某个属性值,如果该值为空,则返回false;如果值不为空,则将该值与havingValue指定的值进行比较,如果一样则返回true;否则返回false。如果返回值为false,则该configuration不生效;为true则生效;
	@Configuration
	@ConditionalOnProperty(prefix = "filter", name = "rabbit", havingValue = "true")
	public class MyRabbitMqMessagelistener {
		......
	}
	只有配置项filter.rabbit=true时, 该Configuration才会生效, 这里是只有配置为true时, 才会去监听rabbitmq对应的topic, queue.
	//该注解详细:https://blog.csdn.net/dalangzhonghangxing/article/details/78420057?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param

17:@AutoConfigureAfter(RedisAutoConfiguration.class)

表示在完成RedisAutoConfiguration的装配后才执行, 
 @AutoConfigureBefore(RedisAutoConfiguration.class)
表示在完成RedisAutoConfiguration的装配前才执行,

18:@Import

	eg:@Import(RedisRepositoriesAutoConfigureRegistrar.class)  表示加载其它的类到当前的环境中来

19:@ConditionnalOnClass

eg: 
	package org.springframework.boot.autoconfigure.data.redis
	**import**
	@Configuration
	@ConditionalClass({JedisConnection.class, RedisOperations.class, Jedis.class})
	@EnableConfigurationProperties(RedisProperties.class)
	public class RedisAutoConfiguration{
		*******
	}
	ConditionalClass:注解中配置了三个类,表示在存在这三个类后, Spring Ioc容器才会去装配RedisAutoConfiguration这个类.
	EnableConfigurationProperties: 注解表示哪个类(RedisProperties.class)可以通过配置文件(application.properties)装配, 这里指定为RedisProperties, 这样就可以通过文件配置了.
	## 20:

@ConditionalOnMissingBean

	eg:
	@Configuration
	protected static class RedisConfiguration {
	@Bean
	@ConditionalOnMissingBean(name = "redisTemplate")
	public RedisTemplate<Object, Object> redisTemplate()
	{	
			****
	}
	}
	ConditionalOnMissingBean:注解表示, 在缺失某些类型的Bean的时候, 才将方法返回的Bean装配到Ioc容器中.  在该处表示, 当Spring Ioc容器中不存在命名为redisTemplate的类时, 才会去装配该函数返回的这个类(redisTemplate).

猜你喜欢

转载自blog.csdn.net/yuyixiong/article/details/107052099
今日推荐