作用:告诉SpringBoot这是配置类,相当于以前的配置文件
基本使用
-
配置类里面使用@Bean标注在方法上给容器注册组件,默认是单实例的
@Bean :给容器中添加组件。
以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例。
可以通过在@Bean注解里面赋值对组件起名,如@Bean("tom")
@Configuration
public class MyConfig {
@Bean
public User user01(){
User zhangsan = new User("zhangsan", 18);
return zhangsan;
}
@Bean("tom")
public Pet pet01(){
return new Pet("tomcat");
}
}
通过控制台输出得知两次获取的是同一对象
@SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
//1.返回我们的IOC容器
ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
//2.从容器中获取组件
Pet tom01 = run.getBean("tom", Pet.class);
Pet tom02 = run.getBean("tom", Pet.class);
System.out.println(tom01==tom02);
}
-
配置类本身也是组件
- @Configuration 注解属性 proxyBeanMethods:代理bean的方法
Full(proxyBeanMethods = true)、【保证每个@Bean方法被调用多少次返回的组件都是单实例的】Lite(proxyBeanMethods = false)【每个@Bean方法被调用多少次返回的组件都是新创建的】
通过从容器获取组件,即可发现proxyBeanMethods为true时使用的时代理方法。
proxyBeanMethods为false,MyConfig组件为 com.atguigu.boot.config.MyConfig@6f95cd51 proxyBeanMethods为true ,MyConfig组件为com.atguigu.boot.config.MyConfig$$EnhancerBySpringCGLIB$$d5d2440@3956b302
- 最佳实践,组件依赖必须使用Full模式(默认)
设置张三对象的宠物必须是tom组件,不能每次获取都要重新创建一个组件,此时必须使用Full模式
@Configuration
public class MyConfig {
@Bean
public User user01(){
User zhangsan = new User("zhangsan", 18);
zhangsan.setPet(pet01());
return zhangsan;
}
@Bean("tom")
public Pet pet01(){
return new Pet("tomcat");
}
}
proxyBeanMethods为ture或false的区别
为false时,可以跳过检查,不会去查找这个组件在容器中是否已经有了,会直接创建新的组件,因此SpringBoot启动就会很快,为true时每一次获取都会检查是否有该组件,启动会很慢。
如果别的组件不依赖我们的组件,可以调整为false,否则,调整为true,可以保证依赖的组件就是容器中的组件。