1. Usage of Bean Injection
2. Configuration class
3. Container class
4. Injected class
package com.example.springexample.autowire; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class AppAutoWire { public static void main(String[] args) { ApplicationContext context =
new AnnotationConfigApplicationContext(AppConfigAutoWire.class); FooService service = (FooService) context.getBean("fooService"); service.method(); FooFormatter formatter = context.getBean(FooFormatter.class); System.out.println(formatter.format()); } }
package com.example.springexample.autowire; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfigAutoWire { @Bean public FooFormatter fooFormatter(){ return new FooFormatter("bean 1"); } @Bean public FooService fooService(){ return new FooService(); } }
package com.example.springexample.autowire; import org.springframework.beans.factory.annotation.Autowired; public class FooService { @Autowired FooFormatter fooFormatter; public void method() { System.out.println("method, " +fooFormatter.format()); } }
package com.example.springexample.autowire; import org.springframework.stereotype.Component; @Component public class FooFormatter { private String param; public FooFormatter(String param) { this.param = param; } public String format(){ return "FooFormatter " + param; } }