Spring Core
Spring Professional Certification
Spring Professional Certification
-
- 1 / 227
-
Flashcards
util Namespace: accessing constants
<util:constants static-field="example.MyConstants.HTTP_PORT" />
public class MyConstants
{
public static final int HTTP_PORT = 80;
}
NOTE: <util:constants> also works with enums!
util Namespace: loading properties
<util:properties location="classpath:mail.properties" />
SpEL context attributes
1) EL attributes can be ...
- named spring beans
- implicit references
2) Some global implicit references are ...
- systemProperties
e.g. #{systemProperties.databaseName}
- systemEnvironment
e.g. #{dbProps.username}
3) more available in web applications
4) extensible through API
- e.g. Spring Security adds 'principle'
3 configuration styles
1) XML-based configuration
(since Spring 1.0 / 2004)
2) Annotation-based configuration
(since Spring 2.5 / 2007)
3) Java-based configuration
(since Spring 3.0 / 2009)
Usage of @Autowired
1) constructor injection
2) method injection
3) field injection
XML vs Annotation-based dependency injection
XML-based dependency injection:
<bean id="transferService class="...">
<constructor-arg ref="accountRepository" />
</bean>
Annotation-based dependency injection:
@Component
public class TransferServiceImpl implements TransferService
{
@Autowired
public TransferServiceImpl(AccountRepository repo) {
this.accountRepository = repo;
}
}
<context:component-scan base-package="com.springsource"/>
NOTE:
- Annotations embeded within POJOs
- minimal xml configuration
@Autowired
indicates that Spring should inject a dependency
1) based on its type (default)
NOTE: only one bean per type!!! => Exception
2) based on its name if used with the @Qualifier annotation
@Autowired
public TransferServiceImp(@Qualifier("accountRepository") AccountRepository repo)
{
this.accountRepository = repo;
}
component scanning: requirements
<context:component-scan base-package="com.springsource" />
=> @Component
=> @Autowired
<context:annotation-config />
=> @PostConstruct
=> @PreDestroy
=> @Required
=> @Autowired
Autowiring and disambiguation / Incorrect
@Component
public class ServiceImpl implements Service
{
@Autowired
public ServiceImpl(Repository repo) { ... }
}
@Component
public class JdbcRepository implements Repository { ... }
@Component
public class HibernateRepository implements Repository { ... }
ATTENTION: Only one bean of a type can be injected!!!
=> NoSuchBeanDefinitionException
Autowiring and disambiguation / Correct
@Component
public class ServiceImpl implements Service
{
@Autowired
public ServiceImpl(@Qualifier("jdbcRepository") Repository repo) { ... }
}
@Component("jdbcRepository")
public class JdbcRepository implements Repository { ...}
@Component("hibernateRepository")
public class HibernateRepository implements Repository { ... }
component names: advantages & characteristics
1) when NOT specified
- names are auto-generated
- never rely on generated names
2) when specified
- less refactoring-friendly
Common strategy:
Avoid names when possible!
stereotype annotations
Annotations that are themselves annotated as @Component
@Service = service classes
@Repository = data access classes
@Controller = web classes (Spring MVC)
@Configuration = Java configuration classes
What are Meta-annotations
annotation which can be used to annotate other annotations
e.g. all service beans should be transactional
<context:component-scan base-package="..." />
=> scans
@MyTransactionalService
public class TransferServiceImpl implements TransferService { ... }
=> recognizes
@Service
@Transactional(timeout=60)
public @interface MyTransactionalService { ... }
@Value with systemProperties
can be used for SpEL expressions in Java code on ...
- field
@Value("#{systemProperties['user.region']}")
private String defaultLocale; - method
@Value("#{systemProperties['user.region']}")
public void setDefaultLocale(String defaultLocale) { ... } - parameter of autowired method or constructor
@Autowired
public void configure(@Value("#{systemProperties['user.region']}") String defaultValue) { ... }
Component scanning:
- What is scanned?
- When is it scanned?
<context:component-scan base-package="..." />
- all classes (incl. jar dependencies) corresponding to base-package
- at startup
component scanning: including & excluding beans
<context:component-scan base-package="ch.homegate.app">
<context:include-filter type="regex" expression="*Repository"/>
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository" />
</context:component-scan>
JSR 330: also known as ... ?
Also known as @Inject
= subset of functionality compared to Spring's @Autowired support
Spring vs JSR 330 annotations
- @Autowired
- @Component
- @Scope
- @Scope("singleton")
- @Qualifier
- @Value
- @Required
- @Lazy
- @Inject
- @Named
- @Scope
- @Singleton
- @Named
- no equivalent
- no equivalent
- no equivalent
Spring annotations are more powerful then standard JSR 330 annotations.
NOTE: can be mixed!
Java-based configuration
- configuration annotations
- advantages
Since Spring 3.0
Configuration annotations:
- @Configuration-annotated classes hold configuration (multiple allowed)
- @Bean methods instead of <bean/> elements
Characteristics & Advantages:
- configuration still external to POJO classes
- more control over bean instantiation and configuration
- more type-safety
@Configuration example
@Configuration
public class ExampleApp
{
@Bean => produces bean definition
public Service service() => bean id
{
Service service = new ServiceImpl();
service.setRepository(repository()); => DI
return service;
}
@Bean
public Repository repository() { ... }
}
How to enable @Configuration class processing?
2 ways
- component scanning, scans @Configuration annotated classes too
<context:component-scan base-package="..."/> - use AnnotationConfigApplicationContext
ApplicationContext ctx = new AnnotationConfigApplicationContext(ExampleConfig.class)
=> no XML required at all!
@Bean methods: characteristics & advantages
- call any code you want
= not just constructors and property setters! - methods may NOT be private
= proxy is used - method name becomes bean id
- same defaults as XML
(e.g. beans are singletons by default)
@Bean @Scope("prototype") to change scope!!!
Java-based configuration: proxy mechanism
- @Bean methods may not be private because proxy needs to call them
- singleton beans are created by default
- proxy first tries to get an instance from context, new instance only is created when no instance is in context
When to use annotation-based configuration?
Pros & Cons
nice for frequently changing beans
+ single place to edit
- configuration spread across your code base
- only works for your own code
When to use XML-based configuration?
Pros & Cons
for infrastructure and more 'static' beans
+ centralized in one (or few) places
+ can be used for all classes (not just your own)
- limited configuration options
When to use Java-based configuration?
Pros & Cons
for full control over instantiation and configuration
+ configuration still external to code
+ integrates well with legacy code
- no equivalent to the XML namespaces
Integration Testing: characteristics
- tests interaction of multiple units of work
- tests application classes in the context of their surrounding infrastructure (e.g. Apache, DB, etc.)
Spring's integration test support:
central support class?
SpringJUnit4ClassRunner
= caches a shared ApplicationContext across test methods
- packaged as separate module spring-test.jar
-
consists of several JUnit test support classes
Annotations for test class
@ContextConfiguration
optional: String-array of config file locations
e.g. @ContextConfiguration("/transfer-context.xml")
default: Spring loads ${classname}-context.xml form same package
@RunWith(SpringJUnit4ClassRunner.class)
= only one ApplicationContext is instantiated for all tests that use the same set of config files (even across test classes)
Annotations for test methods
@Test
= test the system as normal
@DirtiesContext
= forces recreation of cached ApplicationContext if method changes the contained bean
NOTE: ApplicationContext is instantiated only once for all tests that use the same set of config files (even across test classes)!
Annotation for a test dependency
@Autowired
= inject class to be tested
Benefits of Integration Testing with Spring
1) no need to deploy to an external container to test application functionality
=> run everything quickly inside your IDE
2) allows reuse of your configuration between test and production environments
=> application configuration logic is typically reused
=> infrastructure configuration is environment specific
Injecting values with Setter Injection
Scalar values:
<property name="stringProperty" value="foo" />
Automatic Value Type Conversion:
<property name="integerProperty" value="29" />
Injecting lists:
<property name="warehouseList">
<list>
<ref bean="warehouse1" />
...
</list>
</property>
Scoped Proxy
When session-, request- or custom-scoped beans act as dependency of singleton scoped proxy is needed!
- session scoped beans only get instantiated when first user exists
- singleton scoped beans (default) get instatiated only once at startup
=> dependency injection will result in error!!!
SOLUTION:
<bean id="..." class="...">
<aop:scoped-proxy/>
</bean>
importing config files: advantages
- promotes splitting configuration into logical groups
- enables reuse across modules within application
@Inject vs @Autowired
@Inject is a subset of functionality compared to Spring's @Autowired support
@Inject
- has 80% of what you need
@Autowired
- for the rest
@Configuration classes: characteristics
- must have default constructor
(implicit or not) - multiple @Configuration classes may exist
Integration Testing vs Unit Testing
Unit Testing
- tests one unit of functionality
- isolated from the environment
= NO NEED OF SPRING!
Integration Testing
- tests interaction of multiple units working together
- integrates infrastructure
= SPRING PROVIDES GOOD SUPPORT
AOP
Aspect-Oriented Programming
= modularization of cross-cutting concerns
Cross-Cutting Concerns
= generic functionality needed in many places of an application
- Logging and Tracing
- Transaction Management
- Security
- Caching
- Error Handling
- Performance Monitoring