2

This is Spring bean source.

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Bean {
    @AliasFor("name")
    String[] value() default {};

    @AliasFor("value")
    String[] name() default {};

    Autowire autowire() default Autowire.NO;

    String initMethod() default "";

    String destroyMethod() default AbstractBeanDefinition.INFER_METHOD;

I had noticed that String[] value() default {};. It means that we have to use String Array. But I use the code below, passed a String there, It still works, please tell me why.

@Bean("user")
public UserBean get() {
    return new UserBean();
}
Smith Cruise
  • 404
  • 1
  • 4
  • 19

2 Answers2

2

In an array you can put 0 or several values, it's up to you. That simply means that you can give 0 or several aliases to your bean.

@Bean(value={"user","otherUser","..."})
public UserBean get() {
  return new UserBean();
}

EDIT Why "user" is accepted even if it's not an array?

So, in Java you can declare a String object like this :

String value = "value1"; //this is a String
String user = "user"; // this is another String
String str = ""; //this is an empty string

Note that they are defined with "", so "user" is a String.

Now in this case whe have an array of String, that means we have an object which is a container of String.

String[] values=new String[]{};//this is an array of String, an object where we can put many Strings.

As "user" is a String, you can put it int the array values, something like this :

values[0]="user"; 

When you declare you bean like this :

@Bean("user")
public UserBean get() {
  return new UserBean();
}

In reality, you put the String "user" in the array of strings returned by the method :

String[] value() default {};

That why "user" is accepted because it's simply a String

akuma8
  • 4,160
  • 5
  • 46
  • 82
0

This is the same concepts of the main method in Java.

public static void main(String[] args)

You can call your main method passing no parameters, one, two or how many you want.

Serr
  • 303
  • 1
  • 10