You are on page 1of 11

Spring

Annotations
Staticbinding
1.

Normally you declare all the beans or components in XML bean configuration file, so that

Spring container can detect and register your beans or components. Actually, Spring is able to
auto scan, detect and instantiate your beans from pre-defined project package, no more tedious
beans declaration in in XML file.

Note:
Spring supports both Annotation based and XML based configurations. You can even mix
them together. Annotation injection is performed before XML injection, thus the latter
configuration will override the former for properties wired through both approaches.

@Component:To indicate this is class is an auto scan component.

Put this context:component in bean configuration file, it means, enable auto scanning feature
in Spring. The base-package is indicate where are your components stored, Spring will scan this
folder and find out the bean (annotated with @Component) and register it in Spring container.

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context2.5.xsd">

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

</beans

You will noticed that all @Repository , @Service or @Controller are annotated
with @Component . So, can we use just @Component for all the components for auto scanning?
Yes, you can, and Spring will auto scan all your components with @Component annotated.
Its working fine, but not a good practice, for readability, you should always declare
@Repository,@Service or @Controller for a specified layer to make your code more easier to
read, as following :

@Service
Annotate all your service classes with @Service. All your business logic should be in Service
classes.
@Service
public class CompanyServiceImpl implements CompanyService {
.....//bussiness logic
}

@Repository
Annotate all your DAO classes with @Repository. All your database access logic should be
in DAO classes.
@Repository
1
public class CompanyDAOImpl implements CompanyDAO {
2
...
3
}
4
@Component
Annotate your other components (for example REST resource classes) with @Component.

1
2
3
4

@Component
public class ContactResource {
...
}

@Component is a generic stereotype for any Spring-managed component. @Repository,


@Service, and @Controller are specializations of @Component for more specific use cases,
for example, in the persistence, service, and presentation layers, respectively.
@Autowired:
Let Spring auto-wire other beans into your classes using @Autowired annotation.
Here we are autowire dao class to service class
. @Service
public class CompanyServiceImpl implements CompanyService {
@Autowired
private CompanyDAO companyDAO;
...
}

@Transactional:

To activate processing of Spring's @Transactional annotation, use the


<tx:annotation-driven/> element in your spring's configuration file.

@Scope
As with Spring-managed components in general, the default and most common scope for
autodetected components is singleton. To change this default behavior, use @Scope spring
annotation.
@Component
@Scope("request")
public class ContactResource {
...
}

Similarly, you can annotate your component with @Scope("prototype") for beans with
prototype scopes

@Required
In most scenarios, you just need to make sure a particular property has been set, but not all
properties..

For this case, you need @Required annotation


package com.mkyong.common;

import org.springframework.beans.factory.annotation.Required;

public class Customer


{
private Person person;
private int type;
private String action;

public Person getPerson() {


return person;
}
@Required
public void setPerson(Person person) {
this.person = person;
}
}

you also need to register anRequiredAnnotationBeanPostProcessor to aware of the


@Required annotation in bean configuration file.

<context:annotation-config />

<bean id="CustomerBean" class="com.mkyong.common.Customer">


<property name="action" value="buy" />

<property name="type" value="1" />


</bean>

<bean id="PersonBean" class="com.mkyong.common.Person">


<property name="name" value="mkyong" />
<property name="address" value="address ABC" />
<property name="age" value="29" />
</bean>

@Required annotation, it is more flexible than dependency checking in XML file, because it can
apply to a particular property only.

Spring MVC Annotations


@Controller
Controller Process the request and return a ModelAndView object which the

DispatcherServlet will render

public interface Controller {


ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws
Exception;
}

the Controller interface defines a single method handleRequest() that is responsible


for handling a request and returning an appropriate model and view.

@RequestMapping
Annotation for mapping web requests onto specific handler classes and/or handler methods.
@Controller
@RequestMapping("/company")

public class CompanyController {


@Autowired
private CompanyService companyService;
...
}

@PathVariable

You can use the @PathVariable spring annotation on a method argument to bind it to
the value of a URI template variable. In our example below, a request path of
/company/techferry will bind companyName variable with 'techferry' value
@Controller
@RequestMapping("/company")
public class CompanyController {
@Autowired
private CompanyService companyService;
@RequestMapping("{companyName}")
public String getCompany(Map<String, Object> map, @PathVariable
String companyName) {
Company company = companyService.findByName(companyName);
map.put("company", company);
return "company";
}
...
}
@RequestParam
You can bind request parameters to method variables using spring annotation
@RequestParam
@Controller
@RequestMapping("/company")
public class CompanyController {
@Autowired
private CompanyService companyService;
@RequestMapping("/companyList")
public String listCompanies(Map<String, Object> map, @RequestParam int
pageNum) {
map.put("pageNum", pageNum);
map.put("companyList", companyService.listCompanies(pageNum));
return "companyList";

@ModelAttribute

There are several ways to add data or objects to Springs model. Data or objects
are typically added to Springs model via an annotated method in the controller.
In the example below, @ModelAttribute is used to add an instance of
MyCommandBean to the model under the key of myRequestObject.
@SESSIONATTRIBUTES

Springs @SessionAttributes is used on a controller to designate which model attributes


should be stored in the session
In actually, what @SessionAttributes allows you to do is tell Spring which of your model
attributes will also be copied to HttpSession before rendering the view. Again, this can
be demonstrated with a little code.

Spring Security Annotations


@PreAuthorize
Using Spring Security @PreAuthorize annotation, you can authorize or deny a functionality.
In our example below, only a user with Admin role has the access to delete a contact.
@Transactional
@PreAuthorize("hasRole('ROLE_ADMIN')")
public void removeContact(Integer id) {
contactDAO.removeContact(id);
}

SpringFAQs
1. How you will decide when to use prototype scope and when singleton
scope bean?
You should use the prototype scope for all beans that are stateful and the singleton
scope should be used for stateless beans.
2.What is IOC or inversion of control?
As the name implies Inversion of control means now we have inverted the control of
creating the object from our own using new operator to container or framework. Now its
the responsibility of container to create object as required. We maintain one xml file
where we configure our components, services, all the classes and their property. We just
need to mention which service is needed by which component and container will create
the object for us. This concept is known as dependency injection because all object
dependency (resources) is injected into it by framework.

2. Explain Bean-LifeCycle.
Spring Beans are Instantiated / Managed by SpringContainer. These
beans can be created by providing bean specific configuration metadata to
container. Configuration Metadata can be provided in any of below formats.
1.

XML

2.

Annotation

3.

Java Code

When bean is initialized it might require to perform some activity before it can come into use
able state(State in which application can use it) and when bean is getting destroyed there
might be some cleanup activity required for given bean. These activities are known as bean
Lifecycle.
1- IoC container will look for the configuration metadata of given Bean.
2- Once find, container will create the instance of Bean(Using reflection API).
3- After instance creation dependency will be injected(DI).
if Bean Class implements any of the below interface then corresponding method will be
invoked in below order
setBeanName method of BeanNameAware class. It sets the name of the bean in the bean
factory that created this bean.
setBeanFactory method of BeanFactoryAware class. Callback that supplies the owning
factory to a bean instance.

postProcessBeforeInitialization method of BeanPostProcessor. Apply this


BeanPostProcessor to the given new bean instance before any bean
initialization callbacks.
afterPropertiesSet method of InitializingBean. Invoked by a BeanFactory
after it has set all bean properties supplied.
Custom init method will be invoked.
postProcessAfterInitialization methods of BeanPostProcessors. Apply this
BeanPostProcessor to the given new bean instance after any bean
initialization callbacks
DisposableBeans destroy method. Invoked by a BeanFactory on
destruction of a singleton.

How to Call Stored procedure in Spring Framework?


To call a Stored procedure in Spring framework you need to create Class which will
should extends StoredProcedure class.

StoredProcedure class allows you to declare IN and OUT parameters and call
stored procedure using its various execute() method, which has protected access
and can only be called from sub class.

Differentiate between BeanFactory and ApplicationContext in spring.


1. With ApplicationContext more than one config files are possible while only one config file
or .xml file is possible with BeanFactory

2. ApplicationContext support-------------1. internationalization


2. JNDI access, EJB integration, remoting

When do you use programmatic and declarative transaction management ?


- Programmatic

transaction management is used preferably when you have a small number


of transactional operations.
- Incase of large number of transactional operations it is better to use declarative transaction
management.

@transactional
The important attributes of the annotation include:
1.
org.springframework.transaction.annotation.Propagation - The transaction
propagation type
2.
org.springframework.transaction.annotation.Isolation - The transaction
isolation level
3.
readOnly - indicates if the transaction is a read only
4.
rollbackFor - indicates which exceptions should result in a transaction
rollback
5.
noRollbackFor - indicates which exceptions should not result in a transaction
rollback
6.
timeout - transaction timeout limit

@Transactional(readOnly = false, propagation =


Propagation.REQUIRES_NEW)
public void testPersonLifecycle() {}

ISOLATION_READ_UNCOMMITTED :Allows to read changes that havent yet been


committed.It suffer from Scenario 1 ,Scenario 2 ,Scenario 3
ISOLATION_READ_COMMITTED:Allows reads from concurrent transactions that have been
com- mitted.It may suffer from Scenario 2 ,Scenario 3 . Because other transactions may be
updating the data.
ISOLATION_REPEATABLE_READ:Multiple reads of the same field will yield the same results
untill it is changed by itself.It may suffer from Scenario 3.Because other transactions may be
inserting the data
ISOLATION_SERIALIZABLE: Scenario 1,Scenario 2,Scenario 3 never happens.It is complete
isolation.It involves full locking.It affets performace because of locking.

You might also like