spring注解整理(持续更新)

tech2023-01-19  119

1·@configuration

表明当前类等效于一个xml文件没有使用@componentScan,表明所有bean都在此类中定义

2·@bean

返回一个bean,bean的名称为方法名在spring中,容器中存在某个bean,就可以在另一个bean的生命方法的入参中注入

3·AOP两种方式

@Before,@After,@Around,@pointCut,@Aspect

注解形式 自定义一个注解(注解本身是没有功能的,和xml文件一样),将注解标注在目标方法上,方法形式 使用: @Aspect @Component public class LogClass{ @PointCut("@annotation(注解路径)") public void annotationPointCut(){} @After("annotationPointCut()") public void after(JoinPoint point){ MethodSignature ms = (MethodSignature)point.getSignature(); ... } 或者 @Before("execution(路径.Service.*(..))") public void before(JoinPoint point){ MethodSignature ms = (MethodSignature)point.getSignature(); ... } }

开启注解:@EnableAspectjAutoProxy

4·@Value

注入普通字符串 @value(“hello”)注入操作系统属性 @value("#{systemProperties[‘os.name’]}")注入表达式结果 @value(#{T(java.lang.Math).random()*100.0})注入其他的bean属性 @value(“demoService.name”)注入文件 @value(“classpath:com/xxx/test.txt”) private Resource file;注入网址 @value(“http://www.baidu.com”)注入配置文件 @value("${book.value}")和@ConfigurationProperties的区别:@ConfigurationProperties需要setter方法

5·bean的初始化和销毁

使用@bean的时候声明init的destory方法 @bean(initMethod="init",destoryMethod="destory") 增加jsr250-api依赖,在对应方法上添加@postConstruct和@preDestory注解

6·@profile

制定生成bean的运行环境,全局profile配置使用application-{profile}.properties

@bean @profile("dev") public DemoBean getDemoBean(){}

7·spring aware

依赖注入中的bean对容器的存在是没有意识的,即你可以将容器换成其他比如google guicesring aware目的是让bean获得spring容器的服务(beanNameAware,beanFactoryAware,ResourceLoaderAware)加载外部文件 实现ResourceLoaderAware接口重写setResourceLoader方法,设置给本地变量 @override public void setResourceLoader(ResourceLoader resourceLoader){ this.loader = resourceLoader }

使用:

loader.getResource("classpath:com/xxx/text.txt"); @EnableAsync支持异步任务 spring由taskExecutor实现多线程和并发编程,使用threadPoolTaskExecutor实现基于线程池的taskExecutor。在配置类中使用@enableAsync开启支持 @configuration @EnableAsync public class TaskExecutorConfig implement AsyncConfigurer{ @override public Executor getAsyncExecutor(){ threadPooltaskExecutor task = new ThreadPoolTaskExecutor(); task.setCorePoolSize(5); ... return task; } }

4.@Async注解表明该方法是个异步方法,如果注解在类上,表明类的所有方法都是异步方法

@Async public void executeAsyncTask(){ }

5.计划任务@EnableScheduling 首先在配置类注解@EnableScheduling开启对计划任务的支持

6.@sceduled 声明该方法是计划任务

@scheduled(fixedRate = 5000)//没5秒执行一次任务 public void job(){} @scheduled(cron = "0 28 11 ? * *")//每天11点28分执行 public void job(){}

7.@condition条件注解::根据满足某一特定条件串讲一个特定的bean

条件类实现condition接口重写match方法,返回boolean使用时标注在方法上 @bean @condition(条件类.class) public ListService getListService(){...}

8.集成测试

src/test/java ------- src/test/resourcemaven依赖:spring-test,junit测试代码,在src/test/java @RunWith(SpringJUnit4Class\Runner.class) @contextConfiguration(class={testConfig.class})//testConfig返回bean对象 @ActiveProfiles("prod")//声明活动的profile,在返回的bean使用@profile区分bean(@profile("prod")) public class Demo{ @autowired private TestBean bean; @Test public void junitTest(){ ... } }

9.@requestMapping(produces = “text/plain;charset=UTF-8”) produces制定返回的response媒体类型和字符集

@requestMapping(value = "{"/path1","/path2"}"),不同路径可以到相同的方法

10.@pathVariable 访问路径:/anno/pathVar/xx

11.对于访问路径上的key-value,会自动注入到属性或者类中,不需要其他注解

12.使用@autowired可以注入配置类,因为:使用了@component,目的:使用配置类中的属性,不需要每次使用@value单独注入

8·@Inherited

类继承关系中@Inherited的作用

类继承关系中,子类会继承父类使用的注解中被@Inherited修饰的注解

接口继承关系中@Inherited的作用

接口继承关系中,子接口不会继承父接口中的任何注解,不管父接口中使用的注解有没有被@Inherited修饰

类实现接口关系中@Inherited的作用

类实现接口时不会继承任何接口中定义的注解

9·@ConditionalOnClass(CharacterEncodingFilter.class)

当 CharacterEncodingFilter.class在类路径的情况下

10·@ConditionalOnProperties(prefix=“spring.http.encoding”,value=“enabled”,matchIfMissing=true)

matchIfMissing=true,如果没有默认为true,即条件符合

11· @Import

通过@Import或者继承方式使用配置

12·@Enablexxx

声明式事务: @EnableTransactionalManager 不需要显示开启 db缓存:spring boot 默认 concurrentMapCacheManager。使用@EnableCaching 手动开启: @Cacheable(value =“缓存名称”,key = “#user.id”):方法执行前先看缓存,有数据返回缓存,没有调用方法并将返回值放缓存

@CachePut:无论怎样,将方法的返回值放缓存 @CacheEvict:将一条或多条从缓存删除

最新回复(0)