Loading presentation...

Present Remotely

Send the link below via email or IM

Copy

Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.

DeleteCancel

Make your likes visible on Facebook?

Connect your Facebook account to Prezi and let your likes appear on your timeline.
You can change this under Settings & Account at any time.

No, thanks

Spring Dependency Injection Best Practices

No description
by

J. Fernando Escobar

on 7 November 2013

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of Spring Dependency Injection Best Practices

Spring
Spring Training Highlights
BEAN LIFE CYCLE - INITIALIZATION

BEAN LIFE CYCLE - DESTRUCTION

On context.close():



Destroy bean instances if instructed


Destroy itself: the context is not usable again


All destroy methods are called: @PreDestroy, <bean destroy-method=”clearCache” ...>


BEAN LIFE CYCLE - USE

BEAN LIFE CYCLE

OVERVIEW

SPRING FRAMEWORK


Provide infrastructural support for developing enterprise Java applications.


Intends to let you focus on the business problem and avoid repeated handling of:

Object dependencies
Database access and transactions
Security
Messaging
Remote Access
Caching
Testing

Goal

APPLICATION CONTEXT CONFIGURATION

XML



Annotations





Java Code

Types

SPRING

Spring Android

Spring Social

Spring Batch (Nightly Jobs)

Spring Dynamic Modules

Spring Boot

Spring XD

Spring Scala

Spring Insight

Groovy

Spring Framework

Spring Security

Spring MVC

Spring WebFlow

Spring ROO

Spring Web Services

Spring Integration

Spring Data

Spring Mobile

Projects

Spring Dependency Injection Best Practices

System property in the command line
-Dspring.profiles.active=dev

Via web.xml for Web-based application
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>dev</param-value>
</context-param>

Another Way to Activate Profiles

@Component
Indicates a generic auto scan component

@Repository
Indicates a DAO component in the persistence layer

@Service
Indicates a service component in the business layer

@Controller
Indicates a controller component in the presentation layer

Auto Component Scan

<bean class=“com.acme.TestDatabase”>
<property name=“keyGenerator”
value=“#{strategy.databaseKeyGenerator}” />
</bean>

<bean id=“strategy” class=“com.acme.Strategy”>
<property name=“databaseKeyGenerator”
ref=“myKeyGenerator” />
</bean>

<bean id=“calulator” class=“com.acme.Calculator”>
<property name=“defaultLocale”
value=“#{systemProperties[‘user.region’]}” />
</bean>

<security:intercept-url pattern=“/accounts/**”
access=“isAuthenticated() and
hasIpAddress(‘192.168.0.1’)” />

Spring Expression Language (SpEL)

Before
<beans>

<bean id=“service” class=“com.pack.ServiceImpl”>
<constructor-arg ref=“repository” />
<property name=“cust” ref=“custService” />
</bean>

</beans>

After
<beans xmlns:c=“http://www.springframework.org/schema/c”
xmlns:p=“http://www.springframework.org/schema/p” ...>

<bean id=“service” class=“com.pack.ServiceImpl”
c:repository-ref=“repository”
p:cust-ref=“custService” />

</beans>

Power of Namespaces
The c and p namespaces

Power of Namespaces
Profiles
Spring Expression Language (SpEL)
Properties
Parent Beans
Auto Component Scan

Topics

Be more specific rather than “com, org”

<beans>
<context:component-scan base-package=“com.app.persistance,
com.app.service, com.app.controller”>
<context:include-filter type=“regex”
expression=“.*Stub.*Repository” />
<context:exclude-filter type=“annotation”
expression=“com.acme.app.service.MoneyServiceImpl” />
</context:component-scan>
</beans>

@Service
public class TransferServiceImpl implements TransferService {
@Autowired
private Repository repository;
...
}

Auto Component Scan

This can be defined as a subset as well

<beans profile=“dev”>
<jdbc:embedded-database id=“dataSource”>
<jdbc:script location=“classpath:com/sql/data.sql” />
</bean>
</beans>

<beans profile=“production”>
<bean id=“dataSource”
class=“com.oracle.jdbc.pool.OracleDataSource”>
<property name=“URL”
value=“jdbc:oracle:thin:@//server-a:1521/orcl” />
<property name=“user” value=“sysdba-a” />
</bean>
</beans>

Profiles

db-config.properties

db.url=jdbc:oracle:thin:@//localhost:1521/orcl
db.user.name=sysdba

<beans>
<context:property-placeholder
location=“db-config.properties” />
<bean id=“dataSource”
class=“com.oracle.jdbc.pool.OracleDataSource”>
<property name=“URL” value=“${db.url}” />
<property name=“user” value=“${db.user.name}” />
</bean>
</beans>

Properties

Necessary to set the profile before loading XML files

ClassPathXmlApplicationContext appCtx =
ClassPathXmlApplicationContext();

appCtx.getEnvironment().setActiveProfiles(“dev”);

appCtx.setConfigLocations(“classpath:application-config.xml”);

appCtx.refresh();

Activate Profiles Programmatically

Can be more profiles active

@ContextConfiguration(“classpath:application-config.xml”)
@ActivateProfiles(“dev”)
public class TransferServiceTest {
@Autowired
private TransferService transferService;

@Test
public void successTransfer() {
...
}
}

Activate Profiles by Annotation

Overrides property

Overrides property

<beans>
<bean id=“defaultBean” class=“com...OracleDataSource”>
<property name=“URL”
value=“jdbc:oracle:thin:@//server-a:1521/orcl”/>
<property name=“user” value=“sysdba”/>
</bean>

<bean id=“beanB” parent=“defaultBean”>
<property name=“URL”
value=“jdbc:oracle:thin:@//server-b:1521/orcl”/>
</bean>

<bean id=“beanC” parent=“defaultBean”>
<property name=“URL”
value=“jdbc:oracle:thin:@//server-c:1521/orcl”/>
</bean>
</beans>

Default Parent Beans

Will not be instantiated

Overrides property

<beans>
<bean id=“abstractBean”
class=“com...OracleDataSource” abstract=“true”>
<property name=“user” value=“sysdba”/>
</bean>

<bean id=“beanA” parent=“abstractBean”>
<property name=“URL”
value=“jdbc:oracle:thin:@//server-a:1521/orcl”/>
</bean>

<bean id=“beanB” parent=“abstractBean”>
<property name=“URL”
value=“jdbc:oracle:thin:@//server-b:1521/orcl”/>
<property name=“user” value=“monkey”/>
</bean>
</beans>

Abstract Parent Beans

Transactions:
Hide 15 bean definitions

AOP:
Hide 5 bean definitions

Properties:
Hide 1 bean definition

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
...>

<context:property-placeholder
location=“db-config.properties” />

<aop:aspectj-autoproxy />

<tx:annotation-driven />

</beans>

Power of Namespaces
Less Definitions

Types of propagation
REQUIRED – create a new transaction if no transaction exists
REQUIRES_NEW – create a new transaction, even if a transaction already exists
SUPPORTS – if there is a transaction, execute the code inside it. But if there is no transaction, don’t start a new one (makes sense for read-only operations).
…and 4 more that no one ever uses


Transactions, types of propagation and “read-only”

Core AOP concepts:

Aspect - An aspect is a common feature that's typically scattered across methods, classes, object hierarchies, or even entire object models. (It is a behavior, but it’s hard to express its structure in a program’s code using traditional object-oriented techniques.)

Join Point – a single, well defined point in the execution of the code, e.g. execution of a method.

Pointcut – collection of Join Points defining all the conditions that need to be met for the Advice to be executed.

Advice – activity to be performed at a Pointcut


Spring AOP with AspectJ


What’s AOP, and why should I use it?
Spring AOP, a case study: how to make your code cleaner and better
How does Spring AOP work, exactly?

AspectJ: introduction to core AOP concepts

Managing Transactions with Spring AOP

What’s a transaction?
How we manage transactions in MGS using AOP.
Possible alternatives: the @Transactional annotation
How persistence frameworks use the Spring-managed transactions
Manual transaction management with Transaction Callbacks






Spring AOP and transaction management with Spring AOP

Spring AOP in MGS (with AspectJ)

We don’t use it in MGS!

@Transactional can be applied to classes or methods,
and can be parametrized with isolation level etc.

Alternative way of handling transactions: @Transactional

AspectJ weaves binary code around methods during compilation, so for AspectJ no such limitation would apply.

This means that in classic Spring AOP Aspects
will be applied to Spring beans ONLY!

How does Spring AOP apply Aspects?

Spring AOP (no AspectJ)

Spring AOP bean is a… bean.
You can inject other beans into it.

Spring AOP (no AspectJ)

‘Measure the performance of any method you call.’

‘Before you execute any method with “File” in it, check user’s right to do so.’

‘Before you execute any method with “File” in it, log an information about it.’

Case study: getting rid of tangled and scattered code

Monitoring

Security

Tracing

Security



Debugging

Logging

Transactions

AOP – Aspect Oriented Programming, a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns.



AOP makes it possible to avoid code tangling and code scattering.


Leading AOP technologies:
AspectJ:
original AOP technology developed in 1995
uses byte code modifications for aspect weaving, offering extended possibilities, but at the cost of complexity and additional requirements (aspect compliant compiler)
Spring AOP:
uses dynamic proxies for aspect weaving, which imposes some limitations
Simple and intuitive
Supports alternative AspectJ-like syntax for advanced use (e.g. transaction management)


What’s AOP, and why should I use it?
Full transcript