In our previous tutorial, we have declared and configured Spring bean classes using XML configuration file. If you want to reduce the number of XML configuration files, you can do so by configuring the Spring POJO for the Spring IoC container using @Configuration and @Bean annotation.

@Configuration & @Bean Annotations

Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions.

The @Bean annotation tells Spring that a method annotated with @Bean will return an object that should be registered as a bean in the Spring application context.

Let us examine how to use the @Configuration and @Bean annotation to configure the following bean class.

public class Toy {
	private String name;
	private double price;

	public Toy() { }
	public Toy(String name, double price) {
		this.name = name;
		this.price = price;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}
}

The above bean class can be configured using the following XML configuration.

<beans>
   <bean id="crayonToy" class="com.javatechig.spring.bean.Toy" />
</beans>

The following code snippet shows the simplest form of bean declaration using @Configuration and @Bean annotation.

@Configuration
public class MyBeanConfig {

	@Bean
	public Toy crayonToy() {
		return new Toy();
	}
}

Here the method name annotated with @Bean works as bean ID and it creates and returns actual bean instance. Your configuration class can have declaration for more than one @Bean.

Once your configuration classes are defined, you can load & provide them to Spring container using AnnotationConfigApplicationContext class.

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(MyBeanConfig.class);
context.refresh();

Crayon myService = context.getBean(Crayon.class);
This article is about: Spring Core,

Nilanchala

A blogger, a bit of tech freak and a software developer. He is a thought leader in the fusion of design and mobile technologies. He is the author of Xamarin Mobile Application Development for Android Book (goo.gl/qUZ0XV3), DZone MVB and founder of stacktips.com.

Join The Discussion

Please note: We reserve the right to delete comments that contains snarky remarks, offensive or off-topic. To know more read our comments policy.