@Bean注解的有关

    技术2022-07-11  140

    使用@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”})

    Processed: 0.008, SQL: 9