Inversion of Control
Beans can be declared in classes annotated with @Configuration:@Configuration public class ConfigurationClass { private MyService myService = new MyService() { @Override public long getData() { return System.currentTimeMillis(); } }; @Bean public MyService getMyService() { return myService; } } public interface MyService { public long getData(); }
Spring requires a special version of the application context to process annotations:
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.scan("com.jverstry"); ctx.refresh();
Dependency Injection
Other beans classes will want to use declared beans. For example:@Component public class MyServices { private MyService myService; @Autowired public void setMyService(MyService myService) { this.myService = myService; } public MyService getMyService() { return this.myService; } }
MyServices mcs = ctx.getBean(MyServices.class); System.out.println("Data: " + mcs.getMyService().getData());
Data: 1345873585387
Dependencies
Spring annotation processing requires the cglib dependency:<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> <type>jar</type> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2.2</version> </dependency>
More Spring related posts here.
No comments:
Post a Comment