Modern Component Design with Spring
Juergen Hoeller

© 2013 SpringOne 2GX. All rights reserved. Do not distribute without ...
Overview: Spring Component Model Themes
●

Powerful annotated component model

●

Custom annotations through composition

...
Bootstrapping Your Annotated Components
●

Typical: XML bean definition file
–
–

@Component / @Repository / @Service / @C...
A Typical Annotated Component
@Service
public class MyBookAdminService implements BookAdminService {
@Autowired
public MyB...
A More Specific Annotated Component
@Service
@Scope("session")
@Primary
public class MyBookAdminService implements BookAdm...
Composable Stereotype Model
@Service
@Scope("session")
@Primary
@Transactional(rollbackFor=Exception.class)
@Retention(Ret...
Custom Scoping Annotations
@Scope(value="session", proxyMode=ScopedProxyMode.INTERFACES)
@Retention(RetentionPolicy.RUNTIM...
Custom Transaction Annotations
@Transactional(readOnly=false, timeout=10)
@Retention(RetentionPolicy.RUNTIME)
public @inte...
Annotated Factory Methods
@Bean
@Scope("session")
@Primary
public BookAdminService bookAdminService() {
MyBookAdminService...
Configuration Classes
@Configuration
public class MyBookAdminConfig {
@Bean
public BookAdminService myBookAdminService() {...
Configuration with Profile and Enable*
@Configuration
@Profile("standalone")
@EnableTransactionManagement
public class MyB...
EL in Component Annotations
@Repository
public class BookTestDatabase {
@Value("#{systemProperties.databaseName}")
public ...
Composable Annotations Revisited
@Bean
@Scope("session")
@Primary
@Retention(RetentionPolicy.RUNTIME)
public @interface My...
Standardized Annotations
@ManagedBean
@MySessionScoped
public class MyBookAdminService implements BookAdminService {
@Inje...
JSR-330 and Co
●

@javax.inject.Inject is part of JSR-330
–
–

●

"Dependency Injection for Java"
also defines @Scope, @Qu...
JPA Support with Spring Transactions
@Repository
public class MyAccountRepository {
@PersistenceContext
private EntityMana...
Standardized vs. Spring-specific APIs
●

In general, we recommend the use of JSR-330 for DI
–
–

●

JSR-330 @Inject is alm...
Annotated MVC Controllers
@Controller
public class MyMvcController {
@RequestMapping(value = "/books/{id}", method = GET)
...
Portlet MVC Controller
@Controller
@RequestMapping("EDIT")
public class MyPortletController {
@ActionMapping("delete")
pub...
STOMP on WebSocket
@Controller
public class MyStompController {
@SubscribeEvent("/positions")
public List<PortfolioPositio...
Declarative Model Validation
public class Book {

}

@NotNull
@Past
private Date releaseDate;

@RequestMapping("/books/new...
Declarative Formatting
public class Book {

}

@NotNull
@Past
@DateTimeFormat(iso=ISO.DATE)
private Date releaseDate;

pub...
Declarative Scheduling
@Async
public void sendEmailNotifications() {
...
}
@Async
public Future<?> sendEmailNotificationsW...
Declarative Caching
@Cacheable
public Owner loadOwner(int id) {
...
}
@Cacheable(condition="name.length < 10")
public Owne...
Once Again: Spring Component Model Themes
●

Powerful annotated component model

●

Custom annotations through composition...
Upcoming SlideShare
Loading in …5
×

Modern Component Design with Spring

2,063 views

Published on

Speaker: Juergen Hoeller
In recent years, the Spring Framework focuses on flexible and powerful Java-based configuration. This talk presents Spring as an annotation-oriented application framework, illustrating the rich set of features that Spring has to offer for modern component design. General component model trends will be discussed along with selected Spring feature highlights, such as standardized annotations for dependency injection, stereotypes, and declarative services such as validation and scheduling.

Published in: Technology

Modern Component Design with Spring

  1. 1. Modern Component Design with Spring Juergen Hoeller © 2013 SpringOne 2GX. All rights reserved. Do not distribute without permission.
  2. 2. Overview: Spring Component Model Themes ● Powerful annotated component model ● Custom annotations through composition ● Configuration classes and factory methods ● Spring Expression Language ● Flexible MVC/REST controller style ● Declarative validation and formatting ● Declarative scheduling and caching
  3. 3. Bootstrapping Your Annotated Components ● Typical: XML bean definition file – – @Component / @Repository / @Service / @Configuration stereotype – ● <context:component-scan base-package=”com.myapp”/> compare: JPA persistence.xml with @Entity classes Alternative: AnnotationConfigApplicationContext – scan(basePackage) – register(componentClass) – register(configurationClass)
  4. 4. A Typical Annotated Component @Service public class MyBookAdminService implements BookAdminService { @Autowired public MyBookAdminService(AccountRepository ar) { ... } } @Transactional public BookUpdate updateBook(Addendum addendum) { ... }
  5. 5. A More Specific Annotated Component @Service @Scope("session") @Primary public class MyBookAdminService implements BookAdminService { @Autowired @Qualifier("production") public MyBookAdminService(@Lazy AccountRepository ar) { ... } } @Transactional(readOnly=false, timeout=10) public BookUpdate updateBook(Addendum addendum) { ... }
  6. 6. Composable Stereotype Model @Service @Scope("session") @Primary @Transactional(rollbackFor=Exception.class) @Retention(RetentionPolicy.RUNTIME) public @interface MyService {} @MyService public class MyBookAdminService { ... }
  7. 7. Custom Scoping Annotations @Scope(value="session", proxyMode=ScopedProxyMode.INTERFACES) @Retention(RetentionPolicy.RUNTIME) public @interface MySessionScoped {} @Scope(value="session") @Retention(RetentionPolicy.RUNTIME) public @interface MySessionScoped { } ScopedProxyMode proxyMode() default ScopedProxyMode.NO;
  8. 8. Custom Transaction Annotations @Transactional(readOnly=false, timeout=10) @Retention(RetentionPolicy.RUNTIME) public @interface MyTransactional {} @Transactional(rollbackFor=Exception.class) @Retention(RetentionPolicy.RUNTIME) public @interface MyTransactional { } boolean readOnly();
  9. 9. Annotated Factory Methods @Bean @Scope("session") @Primary public BookAdminService bookAdminService() { MyBookAdminService service = new MyBookAdminService(); service.setDataSource(…); return service; } @Bean public BookAdminService bookAdminService() { return MyServiceFactory.createBookAdminService(); }
  10. 10. Configuration Classes @Configuration public class MyBookAdminConfig { @Bean public BookAdminService myBookAdminService() { MyBookAdminService service = new MyBookAdminService(); service.setDataSource(bookAdminDataSource()); return service; } } @Bean public DataSource bookAdminDataSource() { ... }
  11. 11. Configuration with Profile and Enable* @Configuration @Profile("standalone") @EnableTransactionManagement public class MyBookAdminConfig { @Bean public BookAdminService myBookAdminService() { MyBookAdminService service = new MyBookAdminService(); service.setDataSource(bookAdminDataSource()); return service; } } ...
  12. 12. EL in Component Annotations @Repository public class BookTestDatabase { @Value("#{systemProperties.databaseName}") public void setDatabaseName(String dbName) { ... } @Value("#{strategyBean.databaseKeyGenerator}") public void setKeyGenerator(KeyGenerator kg) { ... } } ...
  13. 13. Composable Annotations Revisited @Bean @Scope("session") @Primary @Retention(RetentionPolicy.RUNTIME) public @interface MyBean {} @Autowired @Qualifier("production") @Retention(RetentionPolicy.RUNTIME) public @interface MyAutowired {} @Value("#{systemProperties.databaseName}") @Retention(RetentionPolicy.RUNTIME) public @interface MyDatabaseName {}
  14. 14. Standardized Annotations @ManagedBean @MySessionScoped public class MyBookAdminService implements BookAdminService { @Inject @Named("production") public MyBookAdminService(Provider<AccountRepository> ar) { ... } } @Transactional public BookUpdate updateBook(Addendum addendum) { ... }
  15. 15. JSR-330 and Co ● @javax.inject.Inject is part of JSR-330 – – ● "Dependency Injection for Java" also defines @Scope, @Qualifier, @Named, and Provider interface @javax.transaction.Transactional is part of JTA 1.2 (EE 7) – – ● finally a direct, independent equivalent of Spring's @Transactional previously: just EJB 3.0's @javax.ejb.TransactionAttribute @javax.annotation.ManagedBean is part of JSR-250 v1.1 – can be detected through classpath scanning
  16. 16. JPA Support with Spring Transactions @Repository public class MyAccountRepository { @PersistenceContext private EntityManager em; } @Transactional public void storeAccount(Account account) { this.em.merge(account); }
  17. 17. Standardized vs. Spring-specific APIs ● In general, we recommend the use of JSR-330 for DI – – ● JSR-330 @Inject is almost as capable as Spring's @Autowired can mix and match with Spring's @Value, @Lazy, etc We also recommend the use of JPA 2.x – – ● sufficiently expressive for many purposes now can unwrap down to e.g. a Hibernate Session from a JPA EntityManager However, prefer Spring's stereotype and scoping model – composability is incredibly powerful
  18. 18. Annotated MVC Controllers @Controller public class MyMvcController { @RequestMapping(value = "/books/{id}", method = GET) public Book findBook(@PathVariable("id") long id) { return this.bookAdminService.findBook(id); } } @RequestMapping("/books/new") public void newBook(Book book) { this.bookAdminService.storeBook(book); }
  19. 19. Portlet MVC Controller @Controller @RequestMapping("EDIT") public class MyPortletController { @ActionMapping("delete") public void removeBook(@RequestParam("book") String bookId) { this.myService.deleteBook(bookId); } } @EventMapping("BookUpdate") public void updateBook(BookUpdateEvent bookUpdate) { this.myService.updateBook(…); }
  20. 20. STOMP on WebSocket @Controller public class MyStompController { @SubscribeEvent("/positions") public List<PortfolioPosition> getPortfolios(Principal user) { ... } } @MessageMapping(value="/trade") public void executeTrade(Trade trade, Principal user) { ... }
  21. 21. Declarative Model Validation public class Book { } @NotNull @Past private Date releaseDate; @RequestMapping("/books/new") public void newBook(@Valid Book book, BindingResult br) { } ...
  22. 22. Declarative Formatting public class Book { } @NotNull @Past @DateTimeFormat(iso=ISO.DATE) private Date releaseDate; public class Book { } @DateTimeFormat(iso=ISO.DATE) private LocalDate releaseDate;
  23. 23. Declarative Scheduling @Async public void sendEmailNotifications() { ... } @Async public Future<?> sendEmailNotificationsWithFuture() { return new AsyncResult(...); } @Scheduled(cron = "0 0 12 * * ?") public void performTempFileCleanup() { ... }
  24. 24. Declarative Caching @Cacheable public Owner loadOwner(int id) { ... } @Cacheable(condition="name.length < 10") public Owner loadOwner(String name) { ... } @CacheEvict public void deleteOwner(int id) { ... }
  25. 25. Once Again: Spring Component Model Themes ● Powerful annotated component model ● Custom annotations through composition ● Configuration classes and factory methods ● Spring Expression Language ● Flexible MVC/REST controller style ● Declarative validation and formatting ● Declarative scheduling and caching

×