Spring Core

Spring Professional Certification

Spring Professional Certification


Ursula Fernes
Diese Lernkarten bieten einen umfassenden Einblick in die Spring Core-Funktionen, insbesondere im Bereich der Konfiguration, JMS, RMI und JMX. Sie behandeln Themen wie die Konfiguration von MBeans, die Nutzung von JMS für asynchrone Nachrichtenverarbeitung und die Implementierung von Remote Services mit RMI. Entwickler, die Spring Core für die Erstellung robuster und skalierbarer Anwendungen nutzen möchten, profitieren von diesen Lernkarten, da sie praktische Beispiele und Best Practices für die Integration und Verwaltung von Services bereitstellen.
Flashcards
227
Students
2
Language
German
Category
Computer Science
Level
Other
Created / Updated
21.10.2012 / 30.07.2016

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 ...

  1. field
    @Value("#{systemProperties['user.region']}")
    private String defaultLocale;
  2. method
    @Value("#{systemProperties['user.region']}")
    public void setDefaultLocale(String defaultLocale) { ... }
  3. parameter of autowired method or constructor
    @Autowired
    public void configure(@Value("#{systemProperties['user.region']}") String defaultValue) { ... }

Component scanning:

  1. What is scanned?
  2. When is it scanned?

<context:component-scan base-package="..." />

  1. all classes (incl. jar dependencies) corresponding to base-package
  2. 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

  1. @Autowired
  2. @Component
  3. @Scope
  4. @Scope("singleton")
  5. @Qualifier
  6. @Value
  7. @Required
  8. @Lazy

  1. @Inject
  2. @Named
  3. @Scope
  4. @Singleton
  5. @Named
  6. no equivalent
  7. no equivalent
  8. 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

  1. component scanning, scans @Configuration annotated classes too
    <context:component-scan base-package="..."/>
  2. use AnnotationConfigApplicationContext
    ApplicationContext ctx = new AnnotationConfigApplicationContext(ExampleConfig.class)
    => no XML required at all!

@Bean methods: characteristics & advantages

  1. call any code you want
    = not just constructors and property setters!
  2. methods may NOT be private
    = proxy is used
  3. method name becomes bean id
  4. same defaults as XML
    (e.g. beans are singletons by default)
    @Bean @Scope("prototype") to change scope!!!

Java-based configuration: proxy mechanism

  1. @Bean methods may not be private because proxy needs to call them
  2. singleton beans are created by default
  3. 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

  1. promotes splitting configuration into logical groups
  2. 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

Study