Description and Application Scenario summary in the SSM framework, ssm framework

Source: Internet
Author: User

Description and Application Scenario summary in the SSM framework, ssm framework

Let's talk about component scanning:

If a package path is specified, Spring will automatically scan the package and all its sub-package component classes. When a specific annotation mark is found before the component class definition, the component will be included in the Spring container. It is equivalent to the <bean> definition function in the original XML configuration.

Component scanning can replace <bean> definitions configured in a large number of XML files.

To use component scanning, you must specify the scan class path in the XML configuration.

<Context: component-scan

Base-package = "org. example"/>

In the preceding configuration, all component classes under the org. example package and its sub-package are automatically scanned during container instantiation.

After the scan class path is specified, not all component classes in the path scan to the Spring container. The Spring container is scanned only when the following annotation mark exists before the component class definition.

@ Component: General annotation; @ Name: General annotation; @ Repository: persistence layer Component Annotation

@ Service: Service layer component annotation; @ Controller: control layer component Annotation

When a component is detected during scanning, a default id value is generated. The default id is the class name starting with lowercase. You can also customize the id in the annotation tag. The following two component IDs are respectively oracleUserDao and loginService.

@ Repository

Public class OracleUserDao implements UserDao {

//.....

}

@ Service ("loginService ")

Public class UserService {

//....

}

The default scope of components managed by Spring is "singleton ". If you need other scopes, you can use the @ Scope annotation, as long as the Scope name is provided in the annotation.

@ Scope ("prototype ")

@ Repository

Public class OracleUserDao implements EmpDao {

//...

}

@ PostConstruct and @ PreDestroy annotation mark are used to specify the initialization and destruction callback methods. Example:

Public class ExampleBean {

@ PostConstruct

Public void init (){

// Initialize the callback Method

}

@ PreDestroy

Public void destroy (){

// Destroy the callback Method

}

}

Bean objects with dependencies can be injected using any of the following annotations:

@ Resource

@ Autowired/@ Qualifier

@ Inject/@ Named

 

@ Resource annotation mark can be used before field definition or setter method definition. By default, injection by name is performed first, and injection by type matching is performed:

Public class UserService {

// @ Resource

Private UserDao userDao;

@ Resource

Public void setUserDao (UserDao dao ){

This. userDao = dao;

}

}

An error occurs when multiple matching beans are encountered. You can display the specified name, for example, @ Resource (name = "empDao1 ")

@ Autowired annotation mark can also be used before the field definition or setter method definition. By default, injection by type matching is performed:

Public class UserService {

// @ Autowired

Private UserDao userDao;

@ Autowired

Public void setUserDao (UserDao dao ){

This. userDao = dao;

}

}

@ Autowired injection errors occur when multiple matching beans are encountered. You can use the following method to specify the name:

Public class UserService {

// @ Autowired

// @ Qualifiter ("mysqlUserDao ")

Private UserDao userDao;

@ Autowired

Public void setUserDao (@ Qualifiter ("mysqlUserDao") userDao ){

This. userDao = dao;

}

}

@ Inject annotation mark is added to Spring3.0 to the JSR-330 standard support, before use need to add a JSR-330 jar package, the use method is similar to @ Autowired, such:

Public class UserService {

// @ Inject

Private UserDao userDao;

@ Inject

Public void setUserDao (UserDao dao ){

This. userDao = dao;

}

}

@ Inject injection may cause an error when multiple matching beans are encountered. You can use @ Named to specify the name limitation by using the following method:

Public class UserService {

Private UserDao userDao;

@ Inject

Public void setUserDao (@ Named ("mysqlUserDao") UserDao ){

This. userDao = dao;

}

}

 

@ Value annotation can inject Spring expression values. Usage:

First, specify the properties file to be injected in the XML configuration.

<Util: properties id = "jdbcProps" location = "classpath: db. properties"/>

Use the @ Value annotation before the setter method.

Public class JDBCDataSource {

@ Value ("# {jdbcProps. url }")

Private String url;

@ Value ("# {jdbcProps. driver }")

Public void setUrl (String driver ){

Try {Class. forName (driver)} catch (.....)...

}

}

 

RequestMapping annotation Application

@ RequestMapping can be used in class definition and method definition.

@ RequestMapping indicates which customer request this class or method corresponds

@ RequestMapping can be used to define which requests are processed by the Controller method before the Controller class and before the processing method.

@ Controller

@ RequestMapping ("/demo01 ")

Public class Controller {

@ RequestMapping ("/hello ")

Public String execute () throws Exception {

Return "hello ";

}

}

To enable @ RequestMapping annotation ing, you must define two bean components: RequestMappingHandlerMapping (before class definition) and RequestMappingHandlerAdapter (before method definition) in the Spring XML configuration file.

Example:

<Bean

Class = "org. springframework. web. servlet. mvc. method. annotation. RequestMappingHandlerMapping"/>

<Bean

Class = "org. springframework. web. servlet. mvc. method. annotation. RequestMappingHandlerAdapter"/>

Starting from Spring3.2, you can use the following XML configuration to simplify the definition of RequestMappingHandlerMapping and RequestMappingHandlerAdapter:

<Mvc: annotation-driven/>

 

Controller annotation Application

We recommend that you use the @ Controller annotation to declare the Controller component, which makes the Controller definition more flexible. You do not need to implement the Controller Interface, And you can flexibly define the request processing method.

@ Controller

@ RequestMapping ("/demo01 ")

Public classs Controller {

@ RequestMapping ("/hello ")

Public String execute () throws Exception {

Return "hello ";

}

}

To enable the @ Controller annotation to take effect, you must enable the component scan definition in the Spring XML configuration file and specify the Controller component package.

<Context: component-scan base-package = "com. controller"/>

 

Request parameter value accepted

Spring MVC Web requests can be submitted to the Controller using the following methods:

Use HttpServletRequest to obtain

Use the @ RequestParam Annotation

Encapsulate data into Bean objects using an automatic mechanism

 

Use the @ RequestParam annotation:

Spring automatically injects form parameters into method parameters (with the same name)

Use the @ RequestParam annotation to map inconsistent names.

The advantage parameter type is automatically converted, but a type conversion exception may occur.

@ RequestMapping ("/login-action.form ")

Public String checkLogin (String name, @ RequestParam ("pwd") String password, HttpServletRequest req ){

System. out. println (name );

System. out. println (password );

User user = userService. login (name, password );

// Process

Return "success ";

 

The @ ModelAttribute annotation is used to transmit values to JSP after the Controller component is processed.

(Export: You can also directly use HttpServletRequest and Session, ModeAndView object, ModelMap parameter object, and so on to pass values to the JSP page)

Example:

Use the parameter section of the Controller method or the Bean attribute method.

@ RequestMapping ("login-action.from ")

Public String checkLogin (@ ModelAttribute ("user") User user ){

// Process

Return "success ";

}

@ ModelAttribute ("name ")

Public String getName (){

Return name;

}

(@ ModelAttribute data is transmitted to the JSP page using the Attribute of HttpServletRequest)

@ ExceptionHandler Annotation

@ ExceptionHandler annotation provides Spring MVC Exception Handling Methods

(Example: Spring MVC can handle exceptions in three ways: SimpleMappingExceptionResolver (simple exception processor provided by Spring MVC); Implement the HandlerExceptionResolver interface to customize the exception processor; Use the @ ExceptionHandler annotation to handle exceptions)

@ ExceptionHandler annotation usage:

Public class BaseController {

@ ExceptionHandler

Public String execute (HttpServletRequest req, Exception e ){

Req. setAttribute ("e", e );

// Different view names can be returned Based on the exception type

Return "error ";

}

}

(Suitable for handling exceptions with "processing process)

Then other controllers inherit the BaseController class.

 

@ ResponseBody annotation (in Spring MVC, This annotation is related to the JSON response)

Using the @ ResponseBody Annotation on the Controller method, you can automatically convert the Controller return value (JavaBean) to JSON and send it to the client.

@ ResponseBody annotation is mainly used before the Controller component processing method. The usage is as follows:

Introduce the jackson Development Kit, the following example uses jackson-annotations-2.4.1.jar, jackson-core-2.4.1.jar, jackson-databind-2.4.1.jar

Define <mvc: annotation-driven/> In the Spring configuration file to enable support for the @ ResponseBody application.

Define @ ResponseBody annotation before Controller Processing Method

Example:

Use @ ResponseBody to return a single value:

@ RequestMapping ("/test1 ")

@ ResponseBody

Public boolean f1 (){
// Business processing code

Return true;

}

Use @ ResponseBody to return multiple values:

@ RequestMapping ("/test2 ")

@ ResponseBody

Public Map <String, Object> f2 (){

Map <String, Object> m = new HashMap <String, Object> )();

M. put ("id", 1 );

M. put ("name", "Tom ");

Return m;

}

Use @ ResponseBody to return the List result:

@ RequestMapping ("/test3 ")

@ ResponseBody

Public List <String> f3 (){
List <String> list = new ArrayList <String> ();

List. add ("java ");

List. add ("php ");

List. add ("ui ");

Return list;

}

Return the object result using @ ResponseBody:

@ RequestMapping ("/test4 ")

@ ResponseBody

Public Object f4 (){

Object obj = new Object ();

Return obj;

}

Return the object set result using @ ResponseBody:

@ RequestMapping ("/test5 ")

@ ResponseBody

Public Object f5 (){

Emp e1 = new Emp ();

E1.setId (1 );

E1.setName ("James ");

 

Emp e2 = new Emp ();

E2.setId (2 );

E2.setName ("Li Si ");

 

List <Emp> list = new ArrayList <Emp> ();

List. add (e1 );

; Ist. add (e2 );

Return list;

}

 

Annotation implementation AOP

Development steps:

Creation component:

Creates a class and acts as a component to implement general business logic.

Declaration component:

Enable AOP annotation scanning in applicationContext. xml:

<Aop: aspectj-autoproxy proxy-target-class = "true"/>;

Use the @ Component annotation to identify this class and declare it as a Component.

Use the @ Aspect annotation to identify this class and declare it as an Aspect component.

Usage components:

In the component method, use annotations to apply the aspect component to the method of the target component, and set the notification type to confirm the time when the aspect component is called.

 

Add annotations to the component method using the pre-notification:

@ Before ("within (controller ..*)")

Public void log (){

}

The post-notification and final notification usage methods are the same as those of the pre-notification. You only need to change the annotation to @ AfterReturning and @ After.

Add annotations in the aspect component method for the surround notification:

@ Around ("within (controller ..*)")

Public Object log (ProceedingJoinPoint p) throws Throwable {

// The code is executed before the target component.

Object obj = p. proceed (); // Method for executing the target component

// The code is executed after the target component.

Return obj;

}

For exception notifications, add annotations to the component method:

@ AfterThrowing (pointcut = "within (controller .. *)", throwing = "e ")

Public void log (Exception e ){

}

 

 

@ Transactional Annotation

To implement declarative transactions, follow these steps:

Declare the transaction component in applicationContext. xml and start transaction annotation scanning. For example:

<! -- Declare the transaction management component -->

<Bean id = "txManager"

Class = "org. springframework. jdbc. datasource. DataSourceTransactionManager">

<Property name = "dataSource" ref = "ds"/>

</Bean>

<! -- Enable transaction annotation scanning -->

<Tx: annotation-driven transaction-manager = "txManager" proxy-target-class = "true"/>

The transaction manager txManager specified by transaction-manager needs to be selected based on different database access technologies. For example, JDBC and Mybatis use DataSourceTransactionManager, while Hibernate uses HibernateTransactionManager.

 

Use the @ Transactional annotation to declare a transaction. Use the following method:

@ Transactional

Public class DefaultFooService implements FooService {

// @ Transactional

Public void insertFoo (Foo foo ){...}

Public void updateFoo (Foo foo ){...}

@ Transactional annotation flag can be used before class definition and method definition. The transaction settings of the method take precedence over the transaction settings of class-level annotation.

@ Transactional annotation tags have the following attributes, which can be set as needed:

-Propagation: sets transaction propagation.

-Isolation: sets the transaction isolation level.

-ReadOnly: Set to read-only or read-write.

-RollbackFor: sets which exceptions must be rolled back.

-NoRollbackFor: Used to set which exceptions are not rolled back.

 

@ Transactional annotation attributes are set as follows by default:

The transaction propagation setting is: PROPAGATION_REQUIRED.

Transaction isolation level: ISOLATION_DEFAULT

Transaction is read/write

Transaction timeout is dependent on the transaction system by default, or the transaction timeout is not supported

Any RuntimeException will trigger transaction rollback, but any Checked Exception will not trigger transaction rollback

 

 

@ PathVariable Application

@ PathVariable parses the variables in the URI request template and maps them to the parameters of the processing method. For example:

@ RequestMapping (value = "/emp/{id}", method = requestMethod. GET)

Public String execute (@ PathVariable ("id") int id ){

// Query Operation Processing

Return "";

}

The above URI request template matches/emp/1, emp/2, and other format requests

 

This is the overview of commonly used annotations that are summarized for the time being. There are still some unsummarized annotations that can be understood.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.