18.7k views
2 votes
If using Java-class configuration, what is the default name given to a bean? How can you change this?

1 Answer

2 votes

Answer:

In Java-based Spring configuration, the default name of a bean is the method name declaring it, and you can change it using the name attribute in the Bean annotation.

Step-by-step explanation:

In Spring Framework's Java-based configuration, when you use the Bean annotation to define a bean, the default name of the bean is the name of the method that declares it.

For example:

Configuration

public class MyConfig {

Bean

public MyBean defaultNamedBean() {

// Bean configuration

return new MyBean();

}

}

In this case, the default name of the bean is "defaultNamedBean" based on the method name.

If you want to provide a custom name for the bean, you can use the name attribute of the Bean annotation:

Configuration

public class MyConfig {

Bean(name = "customNamedBean")

public MyBean customNamedBean() {

// Bean configuration

return new MyBean();

}

}

Here, the custom name "customNamedBean" is specified for the bean. This can be useful when you need to refer to the bean using a specific name within your application context.

Thus, In Java-based configuration in Spring, the default name given to a bean is the name of the method that declares the bean.

User Mrtechmaker
by
7.1k points