@Bean is a method-level annotation and a direct analog of the XML <bean/> element.
@Bean
We use it to declare bean. During startup time the bean definition is registered to the ApplicationContext.
ApplicationContext
We can use the @Bean annotation in a @Configuration class.
@Configuration
package com.logicbig.example; public class Calculator { public int sum(int x, int y) { return x + y; } }
package com.logicbig.example; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { @Bean Calculator calculator() { return new Calculator(); } public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); Calculator calculator = context.getBean(Calculator.class); int sum = calculator.sum(5, 7); System.out.println(sum); } }
12
Dependencies and Technologies Used:
Version compatibilities of spring-context with this example:
Versions in green have been tested.