Going Beyond Dependency Injection
By Mark Secrist

© 2013 SpringOne 2GX. All rights reserved. Do not distribute without pe...
A Bit About Me
•  Developer 20+ years
–  C/C++
–  Java/JEE

•  Consultant/Evangelist for Java on HP
–  Promoting Java & JE...
What We’re Going to Cover
•  Overview of Spring Lifecycle
•  Key Patterns used in Spring
–  Programming to Interfaces
–  P...
How We’ll Get There
1.  Introduce the concept
2.  Show examples in the Spring Framework
3.  Discuss ways you can take adva...
Overview of Spring Lifecycle
XML Configuration Instructions
<beans>"
<bean id=“transferService” class=“com.acme.TransferServiceImpl”>"
<constructor-arg...
Creating and Using the Application
// Create the application from the configuration"
ApplicationContext context ="
new Clas...
Using Java Configuration
@Configuration"
public class AppConfig {"
 "
@Bean(“transferService)"
public TransferService transf...
Lifecycle of a Spring ApplicationContext
•  When a context is created the initialization phase
completes
// Create the app...
Bean Initialization Steps
for-each bean ...

Bean
Definitions
Loaded

Post Process
Bean
Definitions

Instantiate
Beans

Lo...
Load Bean Definitions
•  The Bean Definitions are read (ex, XML, Annotation or
JavaConfig)
•  Bean definitions are loaded ...
XML Style Bean Definition Loading
application-config.xml
<beans>
<bean id=“transferService” …
<bean id=“accountRepository”...
The BeanFactoryPostProcessor
•  Useful for applying transformations to groups of bean
definitions
–  Before any objects ar...
A Common Example
<beans ...>"
<context:property-placeholder location=“db-config.properties” />"
"

<bean id=“dataSource” cl...
But Where’s The BeanFactoryPostProcessor?
•  The namespace is just an elegant way to hide the
corresponding bean declarati...
Instantiation and Initialization
Bean
Definitions
Loaded

Bean
Ready
For Use

Post Process
Bean
Definitions

Create Beans
...
Bean Post Processing
•  There are two types of bean post processors
–  Initializers
•  Initialize the bean if instructed
•...
BeanPostProcessor: A Closer Look
•  An important extension point in Spring
–  Can modify bean instances in any way
–  Powe...
Commonly Used Bean Post Processors
•  Activated by <context:annotation-config> (or <context:component-scan>)
–  CommonAnno...
Configuration Lifecycle Summary
Bean
detection BeanFacPP
XML
config
Annotation
config
Java
config

Load xml
definitions

B...
Demo Time
•  Basic configuration
•  Lifecycle
Reminder: The BeanPostProcessor Phase
Bean
Definitions
Loaded

Bean
Ready
For Use

Post Process
Bean
Definitions

Create B...
Spring Uses BeanPostProcessors to:
•  Perform initialization
–  @PostConstruct annotation enabled by
CommonAnnotationBeanP...
Writing a Custom BeanPostProcessor
•  Problem: Spring MVC provides several ExceptionResolver
strategies enabled by default...
Pre-configured Exception Resolvers
<mvc:annotation-driven /> "
"
<!-- With this configuration, three ExceptionResolvers are...
Implementing a BeanPostProcessor
class ExceptionMappingBeanPostProcessor {"
// Use this field to hold the list of resolvers...
Custom BeanPostProcessor Configuration
<mvc:annotation-driven /> "
"
<bean class="com.pivotal.springone.gbdi.ExceptionReso...
Demo Time
•  Spring MVC application with default ExceptionResolver
order
•  Using a custom BeanPostProcessor
Additional Patterns Used in Spring Framework
•  Programming to Interfaces
•  Proxies and AOP
•  Templates
Programming to Interfaces
Example: Programming to Interfaces
public class JdbcAccountRepository implements
AccountRepository {"
…"
}"
Implements a s...
Benefits of Programming to Interfaces
•  Loose Coupling
–  Enables a more pluggable architecture
–  Provide out of the box...
Swapping out Implementations #1
Spring
TransferServiceImpl

JdbcAccountRepository
(1) new JdbcAccountRepository(…);
(2) ne...
Swapping Out Implementations #2
Spring
TransferServiceImpl

JpaAccountRepository
(1) new JpaAccountRepository(…);
(2) new ...
Swapping Out Implementations #3

TransferServiceImpl

StubAccountRepository
(1) new StubAccountRepository();
(2) new Trans...
Interfaces and Spring ApplicationContext
// Create the application from the configuration"
ApplicationContext context ="
ne...
Programming to Interfaces in Spring
•  Core Spring
– 
– 
– 
– 

BeanPostProcessor
BeanFactoryPostProcessor
PlatformTransac...
Spring Security –
the Big Picture
Authentication
Manager

populates

AccessDecision
Manager

polls

delegates

Security In...
Web Security Filter
Configuration
Servlet Container
Web
User

Servlet

DelegatingFilterProxy
FilterChainProxy
Filter
1

Fi...
Looking at Spring Security
<!-- Define the appropriate security namespace and prefix -->"
<beans>"
<!-- Registers a chain of...
Customizing the Authentication Process

Easy Customization
The UserDetails Interface
•  Interface defines required properties
•  Implementation can add additional properties
public ...
The UserDetailsService Interface
•  Interface defines the contract
public interface UserDetailsService { "
UserDetails loa...
Configuring Custom Authentication
•  Configure custom UserDetailsService implementation as a
Spring bean
•  Configure Auth...
Demo Time
•  Implementing custom UserDetails and UserDetailsService
Proxy Power
What is a Proxy?
•  A stand-in for the real object

•  Takes full advantage of Programming to Interfaces
Proxy Usage in Spring
•  FactoryBeans
–  RmiProxyFactoryBean
–  MBeanProxyFactoryBean
–  HttpInvokerProxyFactoryBean

•  S...
Remoting and the ProxyFactoryBean
•  Dynamic proxies generated by Spring communicate with remote
objects
•  Simpler to use...
Basic ProxyFactoryBean Usage
•  Define a factory bean to generate proxy
<bean id=“transferService”
class=“org.springframew...
Spring AOP in a Nutshell
•  Extract cross-cutting concerns into a module that can be
‘woven’ into core functionality befor...
A Simple AOP Logging Example
public class SimpleCache implements Cache
{
public interface Cache {"
private int cacheSize;
...
An AOP Example
•  Implemented as a simple Java class… with annotations
"
@Aspect
public class PropertyChangeTracker {"
pri...
Spring AOP Configuraiton
aspects-config.xml

Configures Spring to apply the

<beans>"
@Aspect to your beans
<aop:aspectj-a...
How Aspects are Applied
setCacheSize()

3. All calls routed
through proxy
interceptor
setCacheSize(2500)

1. Spring create...
JDK vs CGLib Proxies
•  CGLib Proxy

•  JDK Proxy

–  subclass based

–  Interface based
Cache
implements

implements

Spr...
Selecting the Target Methods
•  Pointcut Expression
–  An expression used to select the target methods to intercept with
A...
Spring Transactions in a Nutshell
•  In the code
public class RewardNetworkImpl implements RewardNetwork {"
@Transactional...
How the Proxy Works
•  A BeanPostProcessor may wrap your
beans in a dynamic proxy
–  adds behavior to your application
log...
Giving Meaning to Your Annotations
•  Problem: I want to selectively audit certain operations
within my application using ...
The Target Class
public class JpaOrderRepository implements OrderRepository {
""
public Order findByOrderId(long id) {"
…"
...
The Advice & Pointcut Expression
@Aspect"
Match all methods annotated with
@Component"
@Auditable
public class AuditingAdv...
The Configuration
•  Using XML
<aop:aspectj-autoproxy>
<aop:include name=“auditingAdvice”
</aop:aspectj-autoproxy>
<bean i...
Demo Time
•  Creating and using @Auditable with Spring AOP
Templates
Templates in Spring
•  Objective
–  Define the outline or skeleton of an algorithm
–  Hide away large amounts of boilerpla...
Examples of Templates in Spring
•  Core Spring
–  JdbcTemplate
–  JmsTemplate
–  RestTemplate

•  Spring Data
– 
– 
– 
– 
...
JdbcTemplate Example – convenience functions
int count = template.queryForObject(
“SELECT COUNT(*) FROM CUSTOMER”, Integer...
JdbcTemplate With a Callback Class
List results = jdbcTemplate.query(someSql,
new RowMapper<Customer>() {
public Customer ...
Summary of Callback Interfaces
•  RowMapper
–  Best choice when each row of a ResultSet maps to a domain
object

•  Result...
Demo Time
•  Review ResultSetExtractor usage for customized
UserDetailsService demo
Conclusion
In Summary
•  Spring is MUCH more than just dependency injection
•  Dependency Injection does provide centralized lifecycl...
Spring Stack
Spring Data

Spring for Apache Hadoop

Redis

HBase

GemFire

JPA

QueryDSL

HDFS

MapReduce

Hive

MongoDB

...
Learn More. Stay Connected.

•  msecrist@gopivotal.com

•  Talk to us on Twitter: @springcentral
•  Find Session replays o...
Upcoming SlideShare
Loading in …5
×

Going Beyond Dependency Injection

2,515
-1

Published on

Speaker: Mark Secrist
Many developers who are learning the Spring Framework think of it as simply another mechanism for centralized dependency injection. While the framework does handle that responsibility quite well, the framework is so much more. In this session, we'll explore some of the building blocks and patterns used by the core framework as well as many of the other Spring projects. The result is that attendees will gain a better understanding of how to use the Spring Framework and learn how to build their own components that can leverage these same patterns. Topics we'll explore: - What is the benefit of centralized lifecycle management - Programming to interfaces - Leveraging the power of proxies - Using annotations - Understanding the template pattern
Dependency injection is one very important part of what the Spring Framework does. However, it is also a collection of very key patterns that we'll explore. - Centralized lifecycle management - Examining the BeanFactoryPostProcessor - Examining the BeanPostProcessor - How to write your own BeanPostProcessor - Programming to interfaces - Benefits of programming to interfaces - loose coupling - Examples of how Spring leverages this mechanism - How to leverage in your own Spring applications - Leveraging the power of proxies - How proxies work in Spring - How Spring uses them - Writing your own proxy-based solution - Using annotations - Examples of how Spring uses annotations - Using your own annotations - Understanding the template pattern - Purpose of template pattern - How Spring uses templates - Creating your own template

2 Comments
10 Likes
Statistics
Notes
  • very nice
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Very good presentation on the basics of the Spring
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total Views
2,515
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
92
Comments
2
Likes
10
Embeds 0
No embeds

No notes for slide

Going Beyond Dependency Injection

  1. 1. Going Beyond Dependency Injection By Mark Secrist © 2013 SpringOne 2GX. All rights reserved. Do not distribute without permission.
  2. 2. A Bit About Me •  Developer 20+ years –  C/C++ –  Java/JEE •  Consultant/Evangelist for Java on HP –  Promoting Java & JEE stack on HP Hardware •  Technical Trainer –  –  –  –  –  Core Spring Spring Web Groovy & Grails Gemfire Big Data, Hadoop and Pivotal HD
  3. 3. What We’re Going to Cover •  Overview of Spring Lifecycle •  Key Patterns used in Spring –  Programming to Interfaces –  Proxy Power & AOP –  Templates Goal: Understand how Spring leverages these patterns and learn how to take advantage of them yourself.
  4. 4. How We’ll Get There 1.  Introduce the concept 2.  Show examples in the Spring Framework 3.  Discuss ways you can take advantage
  5. 5. Overview of Spring Lifecycle
  6. 6. XML Configuration Instructions <beans>" <bean id=“transferService” class=“com.acme.TransferServiceImpl”>" <constructor-arg ref=“accountRepository” />" </bean>" " <bean id=“accountRepository” class=“com.acme.JdbcAccountRepository”>" <constructor-arg ref=“dataSource” />" </bean>" " <bean id=“dataSource” class=“org.apache.commons.dbcp.BasicDataSource”>" " <property name=“driverClassName” value=“org.postgresql.Driver” />" " <property name=“URL” value=“jdbc:postgresql://localhost/transfer” />" " …" </bean>" </beans>" "
  7. 7. Creating and Using the Application // Create the application from the configuration" ApplicationContext context =" new ClassPathXmlApplicationContext(“application-config.xml”);" " // Look up the application service interface" TransferService service = " (TransferService) context.getBean(“transferService”);" " // Use the application" service.transfer(new MonetaryAmount(“300.00”), “1”, “2”);" "
  8. 8. Using Java Configuration @Configuration" public class AppConfig {"  " @Bean(“transferService)" public TransferService transferService() {" "TransferService service = new TransferServiceImpl();" "service.setRepository(repository());" "return service;" }" "  " @Bean ! public AccountRepository repository() {" //..." } " ApplicationContext context = new AnnotationConfigApplicationContext(" }" " " " AppConfig.class);"
  9. 9. Lifecycle of a Spring ApplicationContext •  When a context is created the initialization phase completes // Create the application from the configuration" ApplicationContext context = new ClassPathXmlApplicationContext(" “application-config.xml”, " “test-infrastructure-config.xml”" );" •  But what exactly happens in this phase?
  10. 10. Bean Initialization Steps for-each bean ... Bean Definitions Loaded Post Process Bean Definitions Instantiate Beans Load Bean Definitions Dependency Injection Bean Ready For Use BPP BPP Setters Called Initializer Bean Post Processors Create and Initialize Beans BPP BPP
  11. 11. Load Bean Definitions •  The Bean Definitions are read (ex, XML, Annotation or JavaConfig) •  Bean definitions are loaded into the context’s BeanFactory –  Each indexed under its id •  Special BeanFactoryPostProcessor beans are invoked –  Can modify the definition of any bean Bean Definitions Loaded Post Process Bean Definitions Load Bean Definitions
  12. 12. XML Style Bean Definition Loading application-config.xml <beans> <bean id=“transferService” … <bean id=“accountRepository”… </beans> test-infrastructure-config.xml <beans> <bean id=“dataSource” … </beans> Can modify the definition of any bean in the factory before any objects are created Application Context BeanFactory transferService accountRepository dataSource postProcess(BeanFactory) BeanFactoryPostProcessors
  13. 13. The BeanFactoryPostProcessor •  Useful for applying transformations to groups of bean definitions –  Before any objects are actually created •  Several useful implementations are provided by the framework –  You can also write your own –  Implement the BeanFactoryPostProcessor public interface BeanFactoryPostProcessor { public void postProcessBeanFactory (ConfigurableListableBeanFactory beanFactory); }
  14. 14. A Common Example <beans ...>" <context:property-placeholder location=“db-config.properties” />" " <bean id=“dataSource” class=“com.oracle.jdbc.pool.OracleDataSource”>" <property name=“URL” value=“${dbUrl}” />" <property name=“user” value=“${dbUserName}” />" </bean>" </beans> " dbUrl=jdbc:oracle:..." dbUserName=moneytransfer-app" <bean id=“dataSource” class=“com.oracle.jdbc.pool.OracleDataSource”>" <property name=“URL” value=“jdbc:oracle:...” />" <property name=“user” value=“moneytransfer-app” />" </bean>"
  15. 15. But Where’s The BeanFactoryPostProcessor? •  The namespace is just an elegant way to hide the corresponding bean declaration <context:property-placeholder location=“db-config.properties” /> <bean class="org.springframework...PropertySourcesPlaceholderConfigurer"> <property name="location" value="db-config.properties"/> </bean> Implements BeanFactoryPostProcessor PropertySourcesPlaceHolderConfigurer was introduced in Spring 3.1. Prior to that, PropertyPlaceholderConfigurer was used instead
  16. 16. Instantiation and Initialization Bean Definitions Loaded Bean Ready For Use Post Process Bean Definitions Create Beans After Init Initializers Called for-each bean Instantiate Beans Setters Called Before Init Bean Post-Processor(s)
  17. 17. Bean Post Processing •  There are two types of bean post processors –  Initializers •  Initialize the bean if instructed •  Activated by init-method or @PostConstruct –  All the rest! •  Allow for additional richer configuration features •  May run before or after the initialize step After BPP Init Initializer Bean Post Processors Before BPP Init
  18. 18. BeanPostProcessor: A Closer Look •  An important extension point in Spring –  Can modify bean instances in any way –  Powerful enabling feature •  Spring provides many implementations –  Not common to write your own (but you can) public interface BeanPostProcessor { public Object postProcessAfterInitialization(Object bean, String beanName); public Object postProcessBeforeInitialization(Object bean,String beanName); } Post-processed bean Original bean
  19. 19. Commonly Used Bean Post Processors •  Activated by <context:annotation-config> (or <context:component-scan>) –  CommonAnnotationBeanPostProcessor – Handles JSR-250 common annotations (Ex @PostConstruct) –  RequiredAnnotationBeanPostProcessor – Enforces @Required annotation semantics –  AutowiredAnnotationBeanPostProcessor – Enables recognition of @Autowired annotation –  ConfigurationClassPostProcessor – Enables Java Configuration support •  Others that can be configured manually –  PersistenceAnnotationBeanPostProcessor – Enables use of @PersistenceContext in JPA DAO classes –  PersistenceExceptionTranslationPostProcessor – Performs exception translation for classes annotated with @Repository
  20. 20. Configuration Lifecycle Summary Bean detection BeanFacPP XML config Annotation config Java config Load xml definitions Bean instantiation and dependency injection Instantiation & constr. injection BeanPP Property injection @Component scanning Instantiation & @Autowired on constructor Read @Bean method signatures Call @Bean method implementations BeanFacPP → BeanPP → Injection of @Autowired methods & fields BeanFactoryPostProcessor BeanPostProcessor
  21. 21. Demo Time •  Basic configuration •  Lifecycle
  22. 22. Reminder: The BeanPostProcessor Phase Bean Definitions Loaded Bean Ready For Use Post Process Bean Definitions Create Beans After Init Initializers Called for-each bean Instantiate Beans Setters Called Before Init Bean Post-Processor(s)
  23. 23. Spring Uses BeanPostProcessors to: •  Perform initialization –  @PostConstruct annotation enabled by CommonAnnotationBeanPostProcessor •  Perform validation –  JSR 303 validation enabled by BeanValidationPostProcessor •  Add behavior –  @Async annotation enabled by AsyncAnnotationBeanPostProcessor
  24. 24. Writing a Custom BeanPostProcessor •  Problem: Spring MVC provides several ExceptionResolver strategies enabled by default. Processing order is predefined. How do I change the order? •  Solution: 1.  Manually configure the 3 resolvers and set the order property 2.  Use a custom BeanPostProcessor to set the order
  25. 25. Pre-configured Exception Resolvers <mvc:annotation-driven /> " " <!-- With this configuration, three ExceptionResolvers are registered:" ExceptionHandlerExceptionResolver – ExceptionResolver for @Exception annotated methods" ResponseStatusExceptionResolver – ExceptionResolver enabling @ResponseStatus mappings" DefaultHandlerExceptionResolver – ExceptionResolver for mapping exceptions to HTTP status codes" -->" " •  Three ExceptionResolvers are automatically registered •  Order they are consulted by DispatcherServlet is pre-defined •  What if you wanted to change the order?
  26. 26. Implementing a BeanPostProcessor class ExceptionMappingBeanPostProcessor {" // Use this field to hold the list of resolvers by name and their desired order" private Properties exceptionResolvers; !
 " // Implement appropriate getter & setter " ! public Object postProcessBeforeInitialization(Object bean, String beanName)" " " "throws BeansException {" // Check if bean is an instance of ExceptionResolver" // If so, look to see if an order has been defined and assign" // Return the modified bean " "" }" }" "
  27. 27. Custom BeanPostProcessor Configuration <mvc:annotation-driven /> " " <bean class="com.pivotal.springone.gbdi.ExceptionResolverOrderPostProcessor">! <property name="exceptionResolvers">! <value>" "ExceptionHandlerExceptionResolver=2! "ResponseStatusExceptionResolver=3! "DefaultHandlerExceptionResolver=1! </value>" </property>" </bean>" "
  28. 28. Demo Time •  Spring MVC application with default ExceptionResolver order •  Using a custom BeanPostProcessor
  29. 29. Additional Patterns Used in Spring Framework •  Programming to Interfaces •  Proxies and AOP •  Templates
  30. 30. Programming to Interfaces
  31. 31. Example: Programming to Interfaces public class JdbcAccountRepository implements AccountRepository {" …" }" Implements a service interface public class TransferServiceImpl implements TransferService { private AccountRepository accountRepository; } public void setAccountRepository(AccountRepository ar) { accountRepository = ar; Depends on service interface; } conceals complexity of implementation; … allows for swapping out implementation
  32. 32. Benefits of Programming to Interfaces •  Loose Coupling –  Enables a more pluggable architecture –  Provide out of the box components but support for user provided implementations •  Improved Reuse –  A component can often be used wherever interface is expected –  Write once, use multiple places •  Improved Testability –  Ease of swapping a stub implementation for unit testing
  33. 33. Swapping out Implementations #1 Spring TransferServiceImpl JdbcAccountRepository (1) new JdbcAccountRepository(…); (2) new TransferServiceImpl(); (3) service.setAccountRepository(repository); For Jdbc
  34. 34. Swapping Out Implementations #2 Spring TransferServiceImpl JpaAccountRepository (1) new JpaAccountRepository(…); (2) new TransferServiceImpl(); (3) service.setAccountRepository(repository); For Jpa
  35. 35. Swapping Out Implementations #3 TransferServiceImpl StubAccountRepository (1) new StubAccountRepository(); (2) new TransferServiceImpl(); (3) service.setAccountRepository(repository); For Unit Testing
  36. 36. Interfaces and Spring ApplicationContext // Create the application from the configuration" ApplicationContext context =" new ClassPathXmlApplicationContext(“application-config.xml”);" " // Fetch a list of bean names of type BeanPostProcessor" String[] beanNamesOfType = " context.getBeanNamesForType(BeanPostProcessor.class);" " // Fetch a list of beans of type BeanPostProcessor" Map<String,HandlerExceptionResolver> beansOfType = " context.getBeansOfType(HandlerExceptionResolver.class);" " BeanFactoryUtils provides ability to search nested definitions and ancestor BeanFactory
  37. 37. Programming to Interfaces in Spring •  Core Spring –  –  –  –  BeanPostProcessor BeanFactoryPostProcessor PlatformTransactionManager Spring remoting (ex RmiProxyFactoryBean, HttpInvokerProxyFactoryBean) •  Spring MVC –  ViewResolver –  HandlerMapping –  ExceptionResolver (we’ve already seen this one) •  Spring Security –  AuthenticationManager –  FilterChain
  38. 38. Spring Security – the Big Picture Authentication Manager populates AccessDecision Manager polls delegates Security Interceptor protects consults obtains Voters Config Attributes describes thread of execution Security Context Authentication (Principal + Authorities) Secured Resource
  39. 39. Web Security Filter Configuration Servlet Container Web User Servlet DelegatingFilterProxy FilterChainProxy Filter 1 Filter 2 … Spring ApplicationContext Filter N
  40. 40. Looking at Spring Security <!-- Define the appropriate security namespace and prefix -->" <beans>" <!-- Registers a chain of filters including FilterChainProxy -->" <security:http>" …" </security:http>" " " <!-- Registers the appropriate AuthenticationManager and supporting classes-->" <security:authentication-manager>" <security:authentication-provider>" <security:jdbc-user-service data-source-ref=“dataSource” />" </security:authentication-provider>" </security:authentication-manager>" </beans>" "
  41. 41. Customizing the Authentication Process Easy Customization
  42. 42. The UserDetails Interface •  Interface defines required properties •  Implementation can add additional properties public interface UserDetails extends Serializable {" Collection<? extends GrantedAuthority> getAuthorities();" String getPassword();" String getUsername();" boolean isAccountNonExpired();" boolean isAccountNonLocked();" boolean isCredentialsNonExpired();" boolean isEnabled();" }"
  43. 43. The UserDetailsService Interface •  Interface defines the contract public interface UserDetailsService { " UserDetails loadUserByUsername(String username) " throws UsernameNotFoundException;" }" •  Implementation is free to use any approach to satisfy the request –  Read from file –  JDBC Database calls –  Hibernate/JPA/MyBatis, etc •  All the hard work happens here
  44. 44. Configuring Custom Authentication •  Configure custom UserDetailsService implementation as a Spring bean •  Configure AuthenticationProvider to reference it " <!-- Can also be discovered through component scanning --> <bean id="userDetailsService" class="CustomUserDetailsService” ! p:dataSource-ref=”dataSource” />" <security:authentication-manager> <security:authentication-provider user-service-ref="userDetailsService" /> </security:authentication-manager> " " " "
  45. 45. Demo Time •  Implementing custom UserDetails and UserDetailsService
  46. 46. Proxy Power
  47. 47. What is a Proxy? •  A stand-in for the real object •  Takes full advantage of Programming to Interfaces
  48. 48. Proxy Usage in Spring •  FactoryBeans –  RmiProxyFactoryBean –  MBeanProxyFactoryBean –  HttpInvokerProxyFactoryBean •  Spring AOP –  Proxy style weaving using proxies •  Transactions –  Really just implemented using Spring AOP mechanisms •  Spring Data –  Exposed via special repository FactoryBean classes
  49. 49. Remoting and the ProxyFactoryBean •  Dynamic proxies generated by Spring communicate with remote objects •  Simpler to use than traditional RMI stub •  Provides RMI marshalling/unmarshalling + Exception conversion
  50. 50. Basic ProxyFactoryBean Usage •  Define a factory bean to generate proxy <bean id=“transferService” class=“org.springframework.remoting.rmi.RmiProxyFactoryBean”> <property name=“serviceInterface” value=“app.TransferService”/> <property name=“serviceUrl” value=“rmi://foo:1099/transferService”/> </bean> •  Inject it into the client <bean id=“tellerDesktopUI” class=“app.TellerDesktopUI”> <property name=“transferService” ref=“transferService”/> </bean> TellerDesktopUI only depends on the TransferService interface
  51. 51. Spring AOP in a Nutshell •  Extract cross-cutting concerns into a module that can be ‘woven’ into core functionality before application execution •  Modules –  AspectJ uses a separate syntax –  AspectJ also supports annotations on Java classes –  Spring AOP leverages AspectJ annotation style •  Weaving –  Compile-time weaving (AspectJ) –  Load-time weaving (AspectJ) –  Proxy-based weaving (Spring AOP)
  52. 52. A Simple AOP Logging Example public class SimpleCache implements Cache { public interface Cache {" private int cacheSize; public void setCacheSize(int size);" }" private DataSource dataSource; public void setCacheSize(int size) { cacheSize = size; } public void setDataSource(DataSource ds) { dataSource = ds; } }
  53. 53. An AOP Example •  Implemented as a simple Java class… with annotations " @Aspect public class PropertyChangeTracker {" private Logger logger = Logger.getLogger(getClass());" " " @Before(“execution(void set*(*))”) public void trackChange() {" logger.info(“Property about to change…”); " }" }" •  … and some additional Spring configuration
  54. 54. Spring AOP Configuraiton aspects-config.xml Configures Spring to apply the <beans>" @Aspect to your beans <aop:aspectj-autoproxy>" <aop:include name=“propertyChangeTracker” />" </aop:aspectj-autoproxy>" Using " <bean id=“propertyChangeTracker” class=“example.PropertyChangeTracker” />" </beans>" @Configuration" @EnableAspectJAutoProxy" public class AspectConfig {" @Bean(name=”propertyChangeTracker”)" AspectConfig.java public PropertyChangeTracker tracker() {" return new PropertyChangeTracker();" }" }" Using Java XML
  55. 55. How Aspects are Applied setCacheSize() 3. All calls routed through proxy interceptor setCacheSize(2500) 1. Spring creates a proxy 'weaving' aspect & target <<interface>> 2. Proxy implements target interface(s) Spring AOP Proxy (this) Method Interceptor PropertyChange Tracker (aspect) Cache Target   Simple Cache 5. Target method is executed 4. Matching advice is executed
  56. 56. JDK vs CGLib Proxies •  CGLib Proxy •  JDK Proxy –  subclass based –  Interface based Cache implements implements Spring Proxy Extra Logic SimpleCache extends Spring Proxy Target   SimpleCache Extra Logic Target   SimpleCache
  57. 57. Selecting the Target Methods •  Pointcut Expression –  An expression used to select the target methods to intercept with AOP functionality •  Examples execution(void send*(String)) –  Any method starting with send that takes a single String parameter and has a void return type execution(* rewards.*.restaurant.*.*(..)) –  Any methods on any class in a package with one directory between rewards and restaurant execution(@javax.annotation.security.RolesAllowed void send*(..)) –  Any void method starting with send that is annotated with the @RolesAllowed annotation
  58. 58. Spring Transactions in a Nutshell •  In the code public class RewardNetworkImpl implements RewardNetwork {" @Transactional" public RewardConfirmation rewardAccountFor(Dining d) {" // atomic unit-of-work " }" }" •  In the configuration Defines a BeanPostProcessor <tx:annotation-driven/> -proxies @Transactional beans <bean id=“transactionManager” class=”org.springframework.jdbc.datasource.DataSourceTransactionManager”> <property name=“dataSource” ref=“dataSource”/> </bean> <jdbc:embedded-database id="dataSource"> … </jdbc:embedded-database>
  59. 59. How the Proxy Works •  A BeanPostProcessor may wrap your beans in a dynamic proxy –  adds behavior to your application logic transparently
  60. 60. Giving Meaning to Your Annotations •  Problem: I want to selectively audit certain operations within my application using a marker such as an annotation •  Solution: 1.  Create an annotation to act as a marker 2.  Define AOP before advice to capture desired information 3.  Write a pointcut expression to select & apply advice
  61. 61. The Target Class public class JpaOrderRepository implements OrderRepository { "" public Order findByOrderId(long id) {" …" }" Mark these methods as candidates to audit " @Auditable" public Order save(Order entity) {" ..." }" " @Auditable" public @interface Auditable {" public void delete(Order entity) {" // Just a simple interface definition – nothing else required" ..." }" }" }"
  62. 62. The Advice & Pointcut Expression @Aspect" Match all methods annotated with @Component" @Auditable public class AuditingAdvice {! private Logger logger = Logger.getLogger(getClass());! " @Before("execution(@com.pivotal.springone.gbdi.Auditable * *(..))")" public void doAudit(JoinPoint jp) {! "Object target = jp.getTarget();" "logger.info("Audit on " + target.getClass().getSimpleName() + " for method " + 
 jp.getSignature().getName());" }" }"
  63. 63. The Configuration •  Using XML <aop:aspectj-autoproxy> <aop:include name=“auditingAdvice” </aop:aspectj-autoproxy> <bean id=“auditingAdvice” class=”com.pivotal.springone.AuditingAdvice” /> •  Using JavaConfig @Configuration " @EnableAspectJAutoProxy! public class AppConfig {" @Bean" public AuditingAdvice auditingAdvice() {" // Return instantiated and configured AuditingAdvice instance" }" }"
  64. 64. Demo Time •  Creating and using @Auditable with Spring AOP
  65. 65. Templates
  66. 66. Templates in Spring •  Objective –  Define the outline or skeleton of an algorithm –  Hide away large amounts of boilerplate code •  Accomplished by –  Providing convenience functions for simplified usage –  Providing Callback classes to expose specific processing ability
  67. 67. Examples of Templates in Spring •  Core Spring –  JdbcTemplate –  JmsTemplate –  RestTemplate •  Spring Data –  –  –  –  GemfireTemplate JpaTemplate RedisTemplate PigTemplate •  Others –  WebServiceTemplate (Spring Web Services) –  RabbitTemplate (Spring AMQP)
  68. 68. JdbcTemplate Example – convenience functions int count = template.queryForObject( “SELECT COUNT(*) FROM CUSTOMER”, Integer.class); •  Acquisition of the connection •  Participation in the transaction •  Execution of the statement All handled •  Processing of the result set •  Handling any exceptions by Spring •  Release of the connection •  Constructed with a JDBC DataSource JdbcTemplate template = new JdbcTemplate(dataSource);
  69. 69. JdbcTemplate With a Callback Class List results = jdbcTemplate.query(someSql, new RowMapper<Customer>() { public Customer mapRow(ResultSet rs, int row) throws SQLException { // map theclass JdbcTemplate { current row to a Customer object } public List<Customer> query(String sql, RowMapper rowMapper) { }); try { // acquire connection // prepare statement // execute statement // for each row in the result set results.add(rowMapper.mapRow(rs, rowNumber)); return results; } catch (SQLException e) { // convert to root cause exception } finally { // release connection } }
  70. 70. Summary of Callback Interfaces •  RowMapper –  Best choice when each row of a ResultSet maps to a domain object •  ResultSetExtractor –  Best choice when multiple rows of a ResultSet map to a single object •  RowCallbackHandler –  Best choice when no value should be returned from the callback method for each row
  71. 71. Demo Time •  Review ResultSetExtractor usage for customized UserDetailsService demo
  72. 72. Conclusion
  73. 73. In Summary •  Spring is MUCH more than just dependency injection •  Dependency Injection does provide centralized lifecycle, which enables an easy way add and modify objects uniformly •  Some patterns used by Spring that you can also leverage –  Programming to Interfaces Enhanced reuse, lose coupling, improved testability –  Creating and using Proxies Adding incredible power declaratively to your Spring apps –  Templates Hiding the boilerplate and exposing only what’s necessary
  74. 74. Spring Stack Spring Data Spring for Apache Hadoop Redis HBase GemFire JPA QueryDSL HDFS MapReduce Hive MongoDB Neo4j Solr JDBC Splunk Pig Cascading SI/Batch Google App Eng. AWS Beanstalk Heroku Cloud Foundry Spring Batch Spring AMQP Spring XD Spring Web Flow Spring Web Services Spring Social Spring Integration OpenShift Twitter LinkedIn Spring Security Facebook Spring Security OAuth Spring Framework DI AOP TX JMS JDBC ORM OXM Scheduling MVC REST HATEOAS JMX Testing Caching Profiles Expression JTA JDBC 4.1 JMX 1.0+ Tomcat 5+ GlassFish 2.1+ WebLogic 9+ WebSphere 6.1+ Java EE 1.4+/SE5+ JPA 2.0 JSF 2.0 JSR-250 JSR-330 JSR-303
  75. 75. Learn More. Stay Connected. •  msecrist@gopivotal.com •  Talk to us on Twitter: @springcentral •  Find Session replays on YouTube: spring.io/video
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×