Spring Framework
@Bean
Register a factory method and allow its dependencies to be resolved by the container. Spring 7.0.9 instructional lab; source-reviewed, not executed.
Formal Syntax & Structure
java syntaxjava
@Bean Quote quote(Prices prices)Working Example
Example Snippetjava
package lab.spring;import org.springframework.context.annotation.AnnotationConfigApplicationContext;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;public class InjectionDemo { interface Prices { int cents(String sku); } record Quote(Prices prices) { int total(String sku, int quantity) { if (quantity < 1) throw new IllegalArgumentException("quantity"); return Math.multiplyExact(prices.cents(sku), quantity); } } @Configuration(proxyBeanMethods = false) static class Config { @Bean Prices prices() { return sku -> 125; } @Bean Quote quote(Prices prices) { return new Quote(prices); } } public static void main(String[] args) { try (var context = new AnnotationConfigApplicationContext(Config.class)) { System.out.println("quote=" + context.getBean(Quote.class).total("PEN", 3)); } }}