Spring Basics


Spring Basics

Bean lifecycle methods

There are three options for controlling bean lifecycle behavior: custom init() and destroy() methods; the @PostConstruct and @PreDestroy annotations and the

InitializingBean and DisposableBean callback interfaces.

Explain Bean lifecycle in Spring framework

The spring container finds the beans definition from the XML file and instantiates the bean.

Using the dependency injection, spring populates all of the properties as specified in the bean definition.

If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean's ID.

If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.

If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called.

If an init-method is specified for the bean, it will be called.

Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.

What are different types of Autowire types?

byName,byType,constructor,autodetect

AutowireCapableBeanFactory{AUTOWIRE_NO, AUTOWIRE_BY_NAME, AUTOWIRE_BY_TYPE, AUTOWIRE_CONSTRUCTOR, AUTOWIRE_AUTODETECT(@Deprecated)}

What are the different advice types in spring?

Around: Intercepts the calls to the target method

Before: This is called before the target method is invoked

After: This is called after the target method is returned

Throws: This is called when the target method throws and exception


Transaction

Defined in TransactionDefinition:

IsolationLevel

ISOLATION_DEFAULT

ISOLATION_READ_UNCOMMITTED

ISOLATION_READ_COMMITTED

ISOLATION_REPEATABLE_READ

ISOLATION_SERIALIZABLE

Propagation behavior(7 types)

PROPAGATION_REQUIRED

PROPAGATION_SUPPORTS

PROPAGATION_MANDATORY

Support a current transaction; throw an exception if no current transaction exists.

PROPAGATION_REQUIRES_NEW

Create a new transaction, suspending the current transaction if one exists

PROPAGATION_NOT_SUPPORTED

Do not support a current transaction; rather always execute non-transactionally.

PROPAGATION_NEVER

Do not support a current transaction; throw an exception if a current transaction exists.

PROPAGATION_NESTED = 6

Execute within a nested transaction if a current transaction exists, behave like {@link #PROPAGATION_REQUIRED} else.

isReadOnly

Declaratively rolling back a transaction

The recommended way to to roll back a transaction is to throw an Exception.

Be default, Any RuntimeException(unchecked exception) triggers rollback, and any checked Exception does not.

You can configure exactly which Exception types mark a transaction for rollback, including checked exceptions.

Programmatically rolling back a transaction

TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

Default settings

• Propagation setting is REQUIRED.

• Isolation level is DEFAULT.

• Transaction is read/write.

• Any RuntimeException triggers rollback, and any checked Exception does not.

Spring Transaction Example

First configure dataSource and transactionManager in Spring configuration file.

Declarative Transaction through XML

This is the most common as it is non-intrusive, and has the least impact on application code.

expression="execution(* com.mydomain.spring.transaction.declarative.xml.XmlTransactionTestService.*(..))" />

The definition ensures that the transactional advice defined by the txAdvice bean executes at the appropriate points in the program.

Declarative via Annotations

Configure the transaction attributes via annotations in the Java source file.

@Transactional(propagation, isolation, timeout, readOnly, rollbackFor, noRollbackFor)

Programmatic - TransactionTemplate

final TransactionTemplate tt = new TransactionTemplate(transactionManager);

tt.setReadOnly(true);

tt.execute(new TransactionCallbackWithoutResult() {

public void doInTransactionWithoutResult(TransactionStatus status) {

// do stuff

status.setRollbackOnly();

}

});

Spring Event Framework

ApplicationEvent, ApplicationListener, ApplicationEventPublisher.publishEvent(event)

If a Spring bean implements the ApplicationListener, every time an ApplicationEvent gets published to the ApplicationContext, that bean is notified. This is the standard Observer design pattern, we can use it in our Spring-enabled project.

public class EmailService implements ApplicationEventPublisherAware

ApplicationEventPublisher.publishEvent(event);

Hidden features of Spring framework

StringUtilsremoveDuplicateStrings, hasText, capitalize, uncapitalize, getFilenameExtension, stripFilenameExtension

FileCopyUtils.copy

Resources

Spring Transactions - Sample Applications

spring-framework-reference-3.0.pdf

Labels

adsense (5) Algorithm (69) Algorithm Series (35) Android (7) ANT (6) bat (8) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) Java (186) JavaScript (27) JSON (7) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) regex (5) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) xml (5)