@Bean注解的有关

使用@Bean可以把第三方库中的实例交给spring管理,而Component,@Repository,@Controller和@Service局限于自己编写的类!!!

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Bean {
}

以上是@Bean注解的声明,可以看到通过@interface声明以外,还使用了其它的一些注解,这样的话就导致了在使用@Bean注解的时候就会同时有@Target、@Retention、@Documented注解。

@Bean注解码

/**
 * Alias for {@link #name}.
 * <p>Intended to be used when no other attributes are needed, for example:
 * {@code @Bean("customBeanName")}.
 * @since 4.3.3
 * @see #name
 */
@AliasFor("name")
String[] value() default {};

第一行的Alias for {@link #name}可以看出他还有其它的一个名:


/**
 * The name of this bean, or if several names, a primary bean name plus aliases.
 * <p>If left unspecified, the name of the bean is the name of the annotated method.
 * If specified, the method name is ignored.
 * <p>The bean name and aliases may also be configured via the {@link #value}
 * attribute if no other attributes are declared.
 * @see #value
 */
@AliasFor("value")
String[] name() default {};

然后就有name和value这两货在@Bean中是相等的!那么为什么要存在两个相等的东西?
value:属性是默认的在只有使用value一个属性的时候是可以省略写出的@Bean(”xxx“)
,但是有多个属性的时候就要写出对应的名称了@Bean(value=“xxx”,intiMethod=“xxx”);
name:的话再就是更方便人来读代码的时候更容易理解了。

@since 4.3.3的话说的是这个属性在Spring在4.3.3版本开始使用,之前版本不支持。

String[ ] 可以看出返回值是一个String类型的数组,value是属性的名称,default{}表示属性的默认值。结合这几个属性可以得出多个等效的@Bean写法:
1、@Bean == @Bean(value={})
2、@Bean({“x”}) == @Bean(“x”)
3、@Bean(value={“a”,“b”,“c”}) == @Bean({”a“,“b”,“c”})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值