Spring常用注解汇总

作者: 迦叶_金色的人生_荣耀而又辉煌 | 来源:发表于2021-02-17 09:38 被阅读0次

上一篇 <<<手动事务和自定义注解事务代码参考
下一篇 >>>Spring Servlet相关知识


AnnotationConfigApplicationContext 作用:
// @Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext
ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);

1、注解的种类

IOC注解:@Component、@Controller、@Service、@Repository
DI注解:@Autowired、@Resource、@Qualifier、@Inject、@Value
XML注解:@Configuration、@Bean、@ComponentScan、@PropertySource、@Import
其他注解:@Lazy、@Condition、@Primary

2、IOC注解

2.1 @service 、 @Repository注解底层如何实现的

底层都是通过@Component注解实现,主要是为了业务场景的区分,也便于扫包范围的划定。

3、DI注解

3.1 @Autowired、@Resource和@Qualifier等区别

@Autowired默认情况下使用类型查找,会存在问题。SpringBoot多数据源 设置默认或者优先级。
解决方案:
@Resource按照名称查找;
@Qualifier指定实现类

4、XML注解

4.1 @Configuration

@Configuration标注在类上,相当于把该类作为spring的xml配置文件中的<beans>,作用为:配置spring容器(应用上下文)

相当于:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd" default-lazy-init="false">
</beans>

4.2 @Import与@Bean注解的区别

共同点:都是为了引入第三方的bean
区别:
import后面直接跟类名,容器中的id为类的完整名称
bean是通过new手动创建的,容器中的id为方法名称

5、其他注解

5.1 @Lazy

Lazy表示为懒加载,当真正需要引用获取的时候才会被加载
不加或@Lazy(false)情况下为饿汉式,@Lazy和@Lazy(true)为懒汉式

5.2 @Condition

在spring4.0 增加的条件注解,通过这个可以功能可以实现选择性的注入Bean操作

5.3 @Primary

指定实现类的优先级


推荐阅读:
<<<Spring IOC的初始化原理
<<<SpringBean的生命周期流程图
<<<SpringBean单例情况下解决循环依赖的原理
<<<Spring AOP的底层原理
<<<Spring AOP通知责任链模式图解
<<<Spring AOP核心源码解读
<<<Spring事务常识汇总
<<<Spring声明事务原理及核心源码分析
<<<手动事务和自定义注解事务代码参考

相关文章

网友评论

    本文标题:Spring常用注解汇总

    本文链接:https://www.haomeiwen.com/subject/oiyxxltx.html