Spring Annotations
Spring Annotations
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.
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">
</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 {
...
}
@Transactional:
@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..
import org.springframework.beans.factory.annotation.Required;
<context:annotation-config />
@Required annotation, it is more flexible than dependency checking in XML file, because it can
apply to a particular property only.
@RequestMapping
Annotation for mapping web requests onto specific handler classes and/or handler methods.
@Controller
@RequestMapping("/company")
@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
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.
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.
@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