当前位置:网站首页>@Configuration注解的详细介绍
@Configuration注解的详细介绍
2022-07-07 21:53:00 【TPH-BETTER】
转自https://www.cnblogs.com/init-qiancheng/p/14623522.html
@Target({
ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
@AliasFor(
annotation = Component.class
)
String value() default "";
boolean proxyBeanMethods() default true;
}
由该注解定义可知,该注解首先是一个组件,所以会被@SpringBootApplication注解扫描(扫描的前提是该注解必须在与启动类相同包或者子包中) 该注解中有一个属性 proxyBeanMethods,该属性的默认值是true,这个属性可以分为两种模式
- Full模式(即为默认值):proxyBeanMethods = true;
- Lite模式:proxyBeanMethods = false;
Full模式与Lite模式的区别
使用Full模式,这个配置类就被代理,就可以解决组件之间的依赖关系,他会先检查容器中是否存在组件的实例,如果存在就会直接使用,不存在才会进行创建;
如果是Lite模式,就不会产生代理类,每次调用都会执行一次,SpringBoot会跳过在容器中查找的步骤;
什么时候使用Full和Lite
当没有组件依赖的时候就是用Lite,这样会使程序启动更快;
当有组件依赖的时候就是用Full,即为默认值;
MyConfig.java
/** * 1、配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例的 * 2、配置类本身也是组件 * 3、proxyBeanMethods:代理bean的方法 * Full(proxyBeanMethods = true)、【保证每个@Bean方法被调用多少次返回的组件都是单实例的】 * Lite(proxyBeanMethods = false)【每个@Bean方法被调用多少次返回的组件都是新创建的】 * 组件依赖必须使用Full模式默认。其他默认是否Lite模式 */
@Configuration(proxyBeanMethods = false)//告诉SpringBoot这是一个配置类 == 配置文件
public class MyConfig {
/** * Full:外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例对象 * * @return */
@Bean//给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例
public People people() {
return new People(1, "迁承", dog());
}
@Bean
public Dog dog() {
return new Dog(1, "嘻嘻");
}
}
启动类
@SpringBootApplication
public class QianchengApplication {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(QianchengApplication.class, args);
/** * 使用Full模式的时候会输出 * [email protected]7aae97b * true */
/** * 使用Late模式的时候输出 * [email protected] * false */
MyConfig bean = context.getBean(MyConfig.class);
System.out.println(bean);
People people = context.getBean("people", People.class);
Dog dog1 = context.getBean("dog", Dog.class);
System.out.println(people.getDog() == dog1);
}
}
边栏推荐
猜你喜欢
Explain
Benchmarking Detection Transfer Learning with Vision Transformers(2021-11)
激光slam学习(2D/3D、偏实践)
【路径规划】使用垂距限值法与贝塞尔优化A星路径
家用电器行业渠道商协同系统解决方案:助力家电企业快速实现渠道互联网化
List. How to achieve ascending and descending sort() 2020.8.6
Dataguard 主备清理归档设置
2022注册测绘师备考开始 还在不知所措?手把手教你怎么考?
B_QuRT_User_Guide(37)
城联优品作为新力量初注入,相关上市公司股价应声上涨150%
随机推荐
ASP. Net open web page
【7.5】15. 三数之和
Windows set redis to start automatically
USB (XV) 2022-04-14
Dependency injection 2 advantage lifecycle
激光slam学习(2D/3D、偏实践)
通达信买基金安全吗?
B_QuRT_User_Guide(37)
B_QuRT_User_Guide(39)
MySQL Architecture
[stm32+esp8266 connect Tencent cloud IOT development platform 2] stm32+esp8266-01s connect Tencent cloud
Summary of SQL single table query 2020.7.27
C cat and dog
B_ QuRT_ User_ Guide(36)
postgis学习
Open source hardware small project: anxinco esp-c3f control ws2812
Anxin can internally test offline voice module vb-01 to communicate with esp-c3-12f
Slam interview summary
包装行业智能供应链S2B2B商城解决方案:开辟电商消费新生态
2022 届的应届生都找到工作了吗?做自媒体可以吗?