文章目录
底层注解
@Configuration
用于声明配置类,告诉SpringBoot这是一个配置类
Full模式与Lite模式:
参数proxyBeanMethods 默认为true,默认容器添加组件为单例模式,SpringBoot总会检查这个组件是否在容器中已经存在,保证了组件依赖
即每个@Bean方法被调用多少次返回的组件都是同一个对象
向容器中注册组件的方法
1.包扫描(SpringBoot默认扫描包)+注解方式(@Component、@Controller、@Service、@Repository)
SpringBoot默认扫描启动类同级包及子包中的注解
或者在主类使用@ComponentScan(“com.cao”)手动设置扫描包
常用于pojo层/dao层/controller层/service层
2.@Bean导入第三方包
常用于配置类中的方法上声明
方法名:组件的id
返回类型:组件类型
返回的值:组件在容器中的实例
3.@Import方法
类名.class
@Import({User.class, DBHelper.class})
@Conditional条件装配
条件装配:满足Conditional指定的条件,则进行组件注入
@ImportResource导入原生配置文件
比如之前的项目中的xml文件
我们可以使用@ImportResource注解直接导入
@ImportResource("classpath:beans.xml")
@ConfigurationProperties
1.@Component+@ConfigurationProperties
将当前对象注入到ioc容器中,并设置配置绑定
配置文件:
mypet.name="tom"
pojo:
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
@ConfigurationProperties(value = "mypet")
public class Pet {
private String name;
}
controller:
@RestController
public class EmployeeController {
@Resource
Pet pet;
@RequestMapping("pet")
public Pet pet(){
return pet;
}
}
结果:
2.@EnableConfigurationProperties+@ConfigurationProperties
在配置类中添加@EnableConfigurationProperties(Car.class)注解,代替@Conponent将类注入IOC容器中
@EnableConfigurationProperties(Car.class)
//1、开启Car配置绑定功能
//2、把这个Car这个组件自动注册到容器中
public class MyConfig {
}