5. Additional Initialization
• @PostConstruct
Annotations
• Invoked when DI is finished
• @PreDestroy
• Invoked before context is destroyed
@PostConstruct
public void warmup()
Init/Cleanup
{
// initialize using injected properties
}
@PreDestroy
public void teardown()
{
// close connections, send notifications...etc
}
5
7. Spring Context Usage
Create the Context
ApplicationContext ctx = new ClassPathXmlApplicationContext("/path/to/config1.xml","/path/to/config2.xml");
Obtain the Bean
ServiceLocator locator = (ServiceLocator)ctx.getBean("serviceLocator");
Use
URL sererHost = locator.locate("myservice");
Close when done
ctx.close();
7
8. Raising Context Awareness
Create a class that implements Context Awareness
class SpringContext implements ApplicationContextAware
{
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
{
// Do something like caching the context
}
}
Reference it in a configuration file
<bean id="contextAware" class="com.db.fw.entl.context.SpringContext" />
Now, when Spring is done loading the context, it
will invoke SpringContext.setApplicationContext
passing in the context created.
8
9. Life after XML
Spring 3 allows Java-only configuration
Define beans using familiar language
No XML files -- live XML-free
9
10. Spring 3 Annotations
• @Configuration
• Marks a class as a bean provider
• @Bean
• Marks a method as a bean provider
• @Lazy, @Scope, @Primary
• Same goodies you know and love
• @ImportResource
• Interoperability with Spring XML
@Configuration @Lazy @Primary
@Bean @Scope @ImportResource
10
11. Java-only Bean Factory
@Configuration
public class AnnotationConfiguredBeans
{
@Bean
public String greeting()
{
return "Hello World ";
}
@Primary
@Bean
@Lazy
public ComplexValue complex()
{
return new ComplexValue(simpleValue1(), simpleValue2());
}
@Bean
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public SimpleValue simpleValue1()
{
return new SimpleValue("Good Bye“, Math.random()*1000);
}
}
11
12. Annotation Driven Context
Create the Context
ApplicationContext ac = new AnnotationConfigApplicationContext(AnnotationConfiguredBeans.class);
Use it in the same way as you
would an XML generated context.
Programming to an interface
works!
Freedom from the XML tyranny!
12