Current SpringFramework version:
4.1.4
Documentation
Spring Annotations: Contents:
Annotation | Package Detail/Import statement |
---|---|
@Service | import org.springframework.stereotype.Service; |
@Repository | import org.springframework.stereotype.Repository; |
@Component | import org.springframework.stereotype.Component; |
@Autowired | import org.springframework.beans.factory.annotation.Autowired; |
@Transactional | import org.springframework.transaction.annotation.Transactional; |
@Scope | import org.springframework.context.annotation.Scope; |
Spring MVC Annotations | |
@Controller | import org.springframework.stereotype.Controller; |
@RequestMapping | import org.springframework.web.bind.annotation.RequestMapping; |
@PathVariable | import org.springframework.web.bind.annotation.PathVariable; |
@RequestParam | import org.springframework.web.bind.annotation.RequestParam; |
@ModelAttribute | import org.springframework.web.bind.annotation.ModelAttribute; |
@SessionAttributes | import org.springframework.web.bind.annotation.SessionAttributes; |
Spring Security Annotations | |
@PreAuthorize | import org.springframework.security.access.prepost.PreAuthorize; |
For spring to process annotations, add the following lines in your application-context.xml file.
<context:annotation-config /> <context:component-scan base-package="...specify your package name..." />
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. |
@Service
Annotate all your service classes with @Service. All your business logic should be in Service classes.
1
2
3
4
| @Service public class CompanyServiceImpl implements CompanyService { ... } |
@Repository
Annotate all your DAO classes with @Repository. All your database access logic should be in DAO classes.
1
2
3
4
| @Repository public class CompanyDAOImpl implements CompanyDAO { ... } |
@Component
Annotate your other components (for example REST resource classes) with @Component.
1
2
3
4
| @Component public class ContactResource { ... } |
@Autowired
Let Spring auto-wire other beans into your classes using @Autowired annotation.
1
2
3
4
5
6
7
8
| @Service public class CompanyServiceImpl implements CompanyService { @Autowired private CompanyDAO companyDAO; ... } |
Spring beans can be wired by name or by type.
|
@Transactional
Configure your transactions with @Transactional spring annotation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| @Service public class CompanyServiceImpl implements CompanyService { @Autowired private CompanyDAO companyDAO; @Transactional public Company findByName(String name) { Company company = companyDAO.findByName(name); return company; } ... } |
To activate processing of Spring's @Transactional annotation, use the <tx:annotation-driven/> element in your spring's configuration file. |
The default @Transactional settings are as follows:
- Propagation setting is PROPAGATION_REQUIRED.
- Isolation level is ISOLATION_DEFAULT.
- Transaction is read/write.
- Transaction timeout defaults to the default timeout of the underlying transaction system, or to none if timeouts are not supported.
- Any RuntimeException triggers rollback, and any checked Exception does not.
Specifying the @Transactional annotation on the bean class means that it applies to all applicable business methods of the class. Specifying the annotation on a method applies it to that method only. If the annotation is applied at both the class and the method level, the method value overrides if the two disagree. |
@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.
1
2
3
4
5
| @Component @Scope ( "request" ) public class ContactResource { ... } |
Please note that the dependencies are resolved at instantiation time. For prototype scope, it does NOT create a new instance at runtime more than once. It is only during instantiation that each bean is injected with a separate instance of prototype bean. |
Spring MVC Annotations
@Controller
Annotate your controller classes with @Controller.
1
2
3
4
| @Controller public class CompanyController { ... } |
@RequestMapping
You use the @RequestMapping spring annotation to map URLs onto an entire class or a particular handler method. Typically the class-level annotation maps a specific request path (or path pattern) onto a form controller, with additional method-level annotations narrowing the primary mapping.
1
2
3
4
5
6
7
8
| @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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| @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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| @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
An @ModelAttribute on a method argument indicates the argument should be retrieved from the model. If not present in the model, the argument should be instantiated first and then added to the model. Once present in the model, the argument's fields should be populated from all request parameters that have matching names. This is known as data binding in Spring MVC, a very useful mechanism that saves you from having to parse each form field individually.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| @Controller @RequestMapping ( "/company" ) public class CompanyController { @Autowired private CompanyService companyService; @RequestMapping ( "/add" ) public String saveNewCompany( @ModelAttribute Company company) { companyService.add(company); return "redirect:" + company.getName(); } ... } |
@SessionAttributes
@SessionAttributes spring annotation declares session attributes. This will typically list the names of model attributes which should be transparently stored in the session, serving as form-backing beans between subsequent requests.
1
2
3
4
5
6
7
8
9
| @Controller @RequestMapping ( "/company" ) @SessionAttributes ( "company" ) public class CompanyController { @Autowired private CompanyService companyService; ... } |
- @SessionAttribute is initialized when you put the corresponding attribute into model (either explicitly or using @ModelAttribute-annotated method).
- @SessionAttribute is updated by the data from HTTP parameters when controller method with the corresponding model attribute in its signature is invoked.
- @SessionAttributes are cleared when you call setComplete() on SessionStatus object passed into controller method as an argument.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| @Controller @RequestMapping ( "/owners/{ownerId}/pets/{petId}/edit" ) @SessionAttributes ( "pet" ) public class EditPetForm { @ModelAttribute ( "types" ) public Collection<PetType> populatePetTypes() { return this .clinic.getPetTypes(); } @RequestMapping (method = RequestMethod.POST) public String processSubmit( @ModelAttribute ( "pet" ) Pet pet, BindingResult result, SessionStatus status) { new PetValidator().validate(pet, result); if (result.hasErrors()) { return "petForm" ; } else { this .clinic.storePet(pet); status.setComplete(); return "redirect:owner.do?ownerId=" + pet.getOwner().getId(); } } } |
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.
1
2
3
4
5
| @Transactional @PreAuthorize ( "hasRole('ROLE_ADMIN')" ) public void removeContact(Integer id) { contactDAO.removeContact(id); } |
No comments :
Post a Comment