Spring 注解
涉及注解
@AutoWride 根据类型自动装备Bean
@Qualifier 根据bean名称查询bean
@Bean 注解标注方法
@Component 注解标注类
@Target 修饰当前对象类型
示例(@AutoWride @Qualifier @Bean @Component)
初始化数据
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Man {
private Integer age;
}
@Configuration
public class UserInitConfig {
@Bean(value = "xiaoming")
public Man getXM() {
return new Man(18);
}
@Bean(value = "xiaoqiang")
public Man getXQ() {
return new Man(50);
}
}
注入失败
@Component
public class User {
@Autowired
private Man man;
}
启动SpringBoot报错
2023-11-22 09:55:50.323 ERROR 6260 — [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
APPLICATION FAILED TO START
Description:
Field man in com.lc.k1demo03.framework.autowride.User required a single bean, but 2 were found:
xiaoming: defined by method ‘getXM’ in class path resource[com/lc/k1demo03/framework/autowride/UserInitConfig.class]
xiaoqiang: defined by method ‘getXQ’ in class path resource[com/lc/k1demo03/framework/autowride/UserInitConfig.class]
注入成功
@Component
public class User {
@Qualifier(value = "xiaoqiang")
private Man man;
}
启动SpringBoot成功
示例(@Target)
枚举介绍
阅读源码时注意各个注解的作用范围
ElementType.TYPE:类、接口和枚举上
ElementType.FIELD:属性字段上
ElementType.METHOD:方法上
ElementType.PARAMETER:方法参数上
ElementType.CONSTRUCTOR:构造器上
ElementType.LOCAL_VARIABLE:本地局部变量上
ElementType.ANNOTATION_TYPE:注解上
ElementType.PACKAGE:包