Master Spring @Configuration and @Bean: From Java Classes to Fully Configured Beans
Spring’s shift from XML to annotation‑based configuration is explained, covering @Configuration and @Bean requirements, example Java classes, equivalent XML, annotation definitions, bean scopes, component scanning, unit‑testing, and practical tips for wiring beans without field injection, providing a complete guide for modern Spring development.
Introduction
Before Spring 3.0 configuration required XML files; since Spring 3.0 the @Configuration and @Bean annotations enable Java‑based configuration, and Spring Boot has made annotation‑driven setup the default approach.
Java‑based configuration requirements
Configuration classes must not be final.
They must be top‑level (cannot be defined inside another class or be private).
They must provide a public no‑arg constructor.
Basic usage
Annotate a class with @Configuration and annotate factory methods with @Bean. Spring registers the method return values as beans; the default bean name is the method name.
@Configuration
public class DataSourceConfig {
@Bean
public MysqlDataSource mysqlDataSource() {
return new MysqlDataSource();
}
@Bean(name = "oracleDataSource")
public OracleDataSource oracleDataSource() {
return new OracleDataSource();
}
}The same configuration expressed in XML would be:
<bean id="mysqlDataSource" class="com.example.MysqlDataSource"/>
<bean id="oracleDataSource" class="com.example.OracleDataSource"/>@Configuration annotation definition
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
String value() default "";
}Because @Configuration is itself annotated with @Component, it is discovered during component scanning.
@Bean annotation definition and attributes
@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 "(inferred)";
}name / value : specify one or more bean names (equivalent to XML name attribute).
initMethod : method invoked after bean initialization (equivalent to XML init-method).
destroyMethod : method invoked before bean destruction (equivalent to XML destroy-method).
autowire : bean‑property autowiring strategy; possible values are Autowire.BY_NAME, Autowire.BY_TYPE, or Autowire.NO.
Bean scope
@Bean creates a singleton by default. To obtain a prototype bean, add @Scope.
@Bean
@Scope("prototype")
public MysqlDataSource mysqlDataSource() {
return new MysqlDataSource();
}Component scanning
When a package is scanned, Spring detects classes annotated with @Component, @Controller, @Service, @Repository, and also @Configuration because it carries @Component.
Unit‑test example
public class ConfigBeanTest {
@Test
public static void testGetBean() {
ApplicationContext ctx = new AnnotationConfigApplicationContext(DataSourceConfig.class);
MysqlDataSource mysql = ctx.getBean(MysqlDataSource.class);
mysql.print(); // prints "I am MysqlDataSource!"
}
}Practical tip
Instead of autowiring fields inside a @Configuration class, you can call other @Bean methods directly to obtain their instances.
@Bean
public CommonDataSource commonDataSource() {
CommonDataSource common = new CommonDataSource();
common.setMysqlDataSource(mysqlDataSource());
common.setOracleDataSource(oracleDataSource());
return common;
}Note that the setter receives the result of the method call, not a field.
Conclusion
The article demonstrates how @Configuration and @Bean replace XML configuration in modern Spring applications, shows the underlying annotation definitions, bean scopes, component scanning, unit testing, and a practical technique for composing beans without field injection, enabling a smooth migration to annotation‑driven Spring development.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Senior Brother's Insights
A public account focused on workplace, career growth, team management, and self-improvement. The author is the writer of books including 'SpringBoot Technology Insider' and 'Drools 8 Rule Engine: Core Technology and Practice'.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
