@Configuration public class AppConfig { @Bean public MyService myService() { return new MyServiceImpl(); } }
For those more familiar with Spring <beans/>
XML, the AppConfig
class above would be equivalent to:
<beans> <bean id="myService" class="com.acme.services.MyServiceImpl"/> </beans>
public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); MyService myService = ctx.getBean(MyService.class); myService.doStuff(); }
As mentioned above, AnnotationConfigApplicationContext
is not limited to working only with @Configuration
classes. Any @Component
or JSR-330 annotated class may be supplied as input to the constructor. For example:
public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(MyServiceImpl.class, Dependency1.class, Dependency2.class); MyService myService = ctx.getBean(MyService.class); myService.doStuff(); }