Spring Getting Started: Common notes

Related information: https://blog.csdn.net/u010648555/article/details/76299467

 

Spring is a core function of IOC, is to be loaded into the container to initialize Bean, Bean is how to load a container, you can use Spring Annotations way or the Spring XML configuration.
Spring Annotations way to reduce the configuration file content, easier to manage, and use annotations can greatly improve the efficiency of development!
Spring explain below according to the classification of some common notes.

First, the test uses Notes: @RunWith and @ SpringBootTest, @ Test

When a class with @RunWith comments or inherit a class annotated with @RunWith, JUnit will call the class to which it refers to run the class of developers to test and not to build it internally junit.

Second, the sequence control:

JUnit4 Java5 use of annotations (annotation), the following are a few common Annotation JUnit4: 
@Before: initialization method is executed once for each test method (note the BeforeClass difference, which is performed once for all methods)
@After : free up resources for each test method is executed once (note the difference AfterClass, which is performed once for all methods)
@Test: test method, where you can test abnormalities and expectations timeout 
@Test (expected = ArithmeticException.class ) test to check whether the method throws an exception ArithmeticException 
@Ignore: ignore the test method 
@BeforeClass: for all tests, performed only once and must be static void 
@AfterClass: for all tests, performed once only, and must be static void 
a JUnit4 execution order of test units: 
@BeforeClass -> @Before -> @Test -> @After -> @AfterClass; 
call sequence for each test method: 

@Before -> @Test -> @After; 

A: annotation component class
thinking: Spring how to know what should be registered with the Java class as a bean container it?
Answer: ! Need to be addressed are identified using a configuration file or annotations manner java class

1, class notes introduce
@Component: a common standard of spring Bean class.

@Repository: a DAO component class label.

@Service: a business logic component class label.

@Controller: a controller component class label. These are high appearance rate notes in the usual development process,

@ Component, @ Repository, @ Service , @ Controller annotation essentially belong to the same class, the same usage, the same function, except that the type identification component. @Component can replace the @ Repository, @ Service, @ Controller , because these three notes are @Component marked. The following code
@Target (ElementType.TYPE {})
@Retention (RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface the Controller {
    String value () default "";
}
2, Detailed example
(1) when a data access layer component represents (DAO), we use @Repository for annotation, as
@Repository
public class HappyDaoImpl the implements HappyDao {
Private static Logger LOGGER = Final LoggerFactory.getLogger (HappyDaoImpl .class);
public void Club () {
        // do something, like Drinking Singing and
    }
}

(2) when a component representative of the business layer, we use @Service for annotation, as

@Service (value = "goodClubService")
// Use @Service annotations without value, default name is clubService
public class ClubServiceImpl the implements ClubService {
    @Autowired
    Private ClubDao clubDao;
  
    public void doHappy () {
        // do some Happy
    }
 }

(. 3 ) when a control layer as the distal component interaction, using @Controller annotated as follows

@Controller
public class HappyController {
    @Autowired explained below //
    Private ClubService clubService;
    
    // The people Entering The Club Control
    // do something
}
/ * the following comments relating to the Controller explain in detail, a simple introduction @ Controller * / here

3, summary note point
1, annotated java class as a Bean instance, the default instance name Bean is the first letter lowercase Bean class, the other parts unchanged. @Service can also customize Bean name, but must be unique! 2, try using the corresponding components annotated classes replace @Component notes, in a future release of the spring, @ Controller, @ Service, @ Repository will carry more semantics. And to facilitate the development and maintenance! 3, certain classes designated as the Spring Bean class used, preferably spring need to let the search path is specified, was added Spring configuration file as follows:
<! - package and automatically scan all of the specified class in the sub-packets Bean ->
<context: Component Base-Package-Scan =. "org.springframework *" />
II: common bean annotations assembly
1, annotation introduction
@Autowired: the Spring org.springframework.beans.factory.annotation packet belongs, the class attributes may be used to construct, a method of injection-value @Resource: not annotated the spring, but from JSR-250 located java under .annotation package, use the annotation for the specified target bean collaborators bean. @PostConstruct @PreDestroy implemented method and initialization and operation performed before destroying the bean
2, illustration
(1): @ Autowired

@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, 
ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
    boolean required() default true;
}
@Controller
public class HappyController {
    @Autowired //默认依赖的ClubDao 对象(Bean)必须存在
    //@Autowired(required = false) 改变默认方式
    @Qualifier("goodClubService")
    private ClubService clubService;
    
    // Control the people entering the Club
    // do something
}
(2):@Resource

@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)
public @interface Resource {
 String name() default "";
 Class type() default java.lang.Object.class;

public class AnotationExp {

    @Resource (name = "HappyClient")
    Private HappyClient happyClient;
    
    @Resource (type = HappyPlayAno .class)
    Private HappyPlayAno happyPlayAno;
}
. 3, summary
(1): the same effect @Resource point corresponds @Autowired, can be marked in the field or setter method attributes. (2): differs from
a: Provider @Autowired Spring's annotation, @ Resource annotation is javax.annotation, but from JSR-250, J2EE provides required JDK1.6 and above.
b: injection method according to the Type @Autowired injection only; @Resource default automatically injected by Name, Type also provided in accordance with the injection;
C: property
@Autowired annotation can be used to inject the class attribute value, constructors, methods. By default, its dependent objects must exist (the bean available), if the need to change this default, it may be required attribute set to false.
There is also a more important point is, @ Autowired default annotation by type assembly, if the container contains more of the same type of Bean, then an exception can not find the specified type will be reported at startup bean container, the solution is a combination ** @ qualifier ** annotations are defined to specify the name of the injected bean.
@Resource There are two important attributes: name and type. The name attribute specifies byName, if no name attribute, when annotations marked on the field, i.e., the default name taken field as the bean name Looking dependent objects when annotations marked on the setter method attributes, the default takes the property name as the bean name Looking dependent objects.
Note that, @ Resource If you do not specify the name attribute, and still can not find dependent objects in accordance with the default name, @Resource notes will fall back by type assembly. But once the name attribute is specified, it is only by name equipped.

d: @Resource use of more flexible annotation, you specify a name, you can also specify the type; @Autowired comment assembled easily throw an exception, especially bean type equipped with a plurality of time, and the solution is needed @Qualifier increase limit.

@Autowired difference in Spring annotation and annotation @Resource

Precautions: Use @Resource should also pay attention to add profile Spring, Scan-if not configured the Component
<context: the Component-Scan> 
! <- <context: the Component-Scan> use, is activated by default <context: annotation- config> features ->

you must configure the annotation-config

<context: annotation-config />

three: VS @Component @Configuration and @Bean
1, briefly
Spring official said the team may replace @Component @Configuration notes, in fact, we look to see the source code can also be found as follows
@Target ( ElementType.TYPE} {)
@Retention (RetentionPolicy.RUNTIME)
@Documented
@Component // look here! ! !
@interface the Configuration {public
    String value () default "";
although you can replace, but there are differences between the two notes!

Bean used when the method is mainly used for notes, somewhat similar to the factory method, when used @Bean annotation, we can continuously use a variety of definitions bean notes, for example, with the name of the custom factory @Qualifier annotation methods, annotated with @Scope define the scope of the scope of the bean, and the like such as a prototype or a singleton.

Spring in the new core Java configuration support is @Configuration annotated classes. These classes include methods @Bean annotations to define an object instance Spring IoC container management, configuration, and initialization logic.

@Configuration used to annotate classes represent classes can be used Spring IoC container, as a resource definition bean.

@Configuration
public class AppConfig {
    @Bean
    public the MyService myService () {
        return new new MyServiceImpl ();
    }
}

This Spring XML file is very similar to

<Beans>
    <bean the above mentioned id = "myService" class = "com.acme.services.MyServiceImpl" />
</ Beans>

@Bean notes and elements played the same role.

2, and illustrates @Component @Configuration
@Configuration
public static class Config {

    @Bean
    public SimpleBean simpleBean() {
        return new SimpleBean();
    }

    @Bean
    public SimpleBeanConsumer simpleBeanConsumer() {
        return new SimpleBeanConsumer(simpleBean());
    }
}

@Component
public static class Config {

    @Bean
    public SimpleBean simpleBean() {
        return new SimpleBean();
    }

    @Bean
    public SimpleBeanConsumer simpleBeanConsumer () {
        return new new SimpleBeanConsumer (SimpleBean ());
    }
}

The first code work, as expected, SimpleBeanConsumer will be linked in a single embodiment SimpleBean. The second configuration is completely wrong, because Spring will create a singleton bean SimpleBean, but SimpleBeanConsumer SimpleBean will receive another example (which is equivalent to a direct call new SimpleBean (), the Spring bean is not owned by management), both new SimpleBean () examples are outside the control Spring context.

3 reasons summarized
using the @ configuration, all labeled @ bean methods will be packaged into a CGLIB wrapper, it works as if the first call this method, then the body of the original method will be executed, the final the object is registered in the spring context. All further call returns only retrieved from the context bean.
In the above second code block, the new SimpleBeanConsumer (simpleBean ()) call only a pure java method. In order to correct the second block of code, we can do this

@Component
public static class Config {
    @Autowired
    SimpleBean simpleBean;

    @Bean
    public SimpleBean simpleBean() {
        return new SimpleBean();
    }

    @Bean
    public SimpleBeanConsumer simpleBeanConsumer() {
        return new SimpleBeanConsumer(simpleBean);
    }
}

Spring @Configuration vs @Component
基本概念:@Configuration 和@Bean

Four: spring MVC annotation module
1, web module used to annotation
@Controller: This class will show as a control layer assembly for interacting with the front end, by an act of providing access to an application service interface definition, interpreting user input, convert it into a model and then attempt that was presented to the user.
@Controller
public class HappyController {
    // do something
...
}

the Spring @Controller defined using the MVC controller, it allows automatic detection of defined components (scan path configuration in the configuration file) in the class path and automatically registered.

@RequestMapping: url This annotation map for the entire class or specific processing method for processing a request. Wildcards can be used only!
@Controller
@RequestMapping ( "/ Happy")
public class HappyController {

  @Autowired
  Private HappyService happyService;
  
  @RequestMapping (/ Hello / *)
  public void the sayHello () {
        // request is / happy / hello / * This method will enter!
        // For example: / Happy / Hello / 123 / Happy / Hello / the adb
        // can get / post request
  }
  @RequestMapping (value = "/ haha", Method = RequestMethod.GET)
  public void sayHaHa () {
  // Only can get request
  }
...
}

@RequestMapping may be acting at the class level, may also act in the process level. When it is defined in the class level, indicating that the controller processes all requests are mapped to / favsoft path. @RequestMapping type methods may be used in the method attribute tag to him or her, if not specified, then the type of method, the data may be requested using HTTP GET / POST method, but once the type specified method, can use only the type of data acquisition.

@RequestParam: the requested parameter bound to the process parameters, there are required parameters, default, required = true, i.e. change parameter must be passed. If the changed transmission parameter may be passed, you may be configured required = false.
 @RequestMapping ( "/ Happy")
  public String sayHappy (
  @RequestParam (value = "name", required to false =) String name,
  @RequestParam (value = "Age", required to true =) String Age) {
  // parameters must Age transmission, name may not be available for transmission
  ...
  }

@PathVariable: annotation method for modifying the parameters of the method, the method will be modified parameter becomes available uri variable (dynamic binding may be used).
@RequestMapping (value = "/ Happy / {dayid}", Method = RequestMethod.GET)
public String findPet (@PathVariable String dayid, the Model MODE) {
// @PathVariable annotations using the binding {dayid} dayid String
}

@PathVariable the parameters can be any simple type, such as int, long, Date and so on. Spring will automatically be converted to the appropriate type or TypeMismatchException thrown exception. Of course, we can also register support additional data types.
@PathVariable supports the use of regular expressions, which determines its super large property, you can use placeholders in the template path can be set to match specific prefix, suffix, matching a custom format.

@RequestBody: @RequestBody parameter refers to a method should be bound to the HTTP request the Body.
@RequestMapping (value = "/ something", Method = RequestMethod.PUT)
{public void handle (String @RequestBody body, the User User @ requestBody)
   object type can be bound // custom
}

@ResponseBody: @ResponseBody and @RequestBody Similarly, its role is directly input to the return type of the HTTP response body.
@ResponseBody when outputting data in JSON format, it will be frequently used.
@RequestMapping (value = "/ Happy", Method = RequestMethod.POST)
@ResponseBody
public String the helloWorld () {    
return "the Hello World"; // return a String
}

@RestController: controllers of the REST API, serve only in JSON, XML or other custom content types, @ RestController used to create REST type of controller, and @Controller type. @RestController is such a type, it avoids you repeat writing @RequestMapping and @ResponseBody.

@ModelAttribute: @ModelAttribute may act on the method or process parameters when it acts on the method, the object method is indicated to add one or more attributes model (model attributes).
This approach allows the same parameters @RequestMapping type, but can not be directly mapped to the request. @ModelAttribute method and the controller gets called before @RequestMapping method call.

@ModelAttribute There are two styles: one is to add stealth property and return it. Another method is that the model takes a model and add any number of attributes. The user can select the corresponding style according to their needs.

Five: Spring annotation transaction module
1, to the annotations used
in processing the transaction or the service layer operations dao layer, such rollback delete operation fails. ** @ Transactional ** use as a comment, but you need to activate the configuration file
<- Open comments declarative transaction -!>
    <Tx: Transaction-Driven-Annotation Manager = "transactionManager" />
1
2
2, for example
@Service
CompanyServiceImpl the implements CompanyService {class public
  @Autowired
  Private companyDAO companyDAO;

  @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)
  public int deleteByName(String name) {

    companyDAO.deleteByName the Result = int (name);
    return the Result;
  }
  ...
}

3, summarizes
the transaction propagation mechanisms and isolation mechanism is more important!
Transaction Type Description propagation behavior
PROPAGATION_REQUIRED If no transaction creates a new transaction, if there is already a transaction, added to this transaction. This is the most common choice.
PROPAGATION_SUPPORTS support the current transaction, if no transaction is executed in a non-transactional way.
PROPAGATION_MANDATORY use the current transaction, if no transaction, throw an exception.
PROPAGATION_REQUIRES_NEW New Transaction, if the current transaction exists, the current transaction pending.
PROPAGATION_NOT_SUPPORTED perform operations to a non-transactional way, if the current transaction exists, put the current transaction pending.
PROPAGATION_NEVER to perform non-transactional way, if the current transaction exists, an exception is thrown
PROPAGATION_NESTED if the current transaction exists, it is executed within nested transactions. If no transaction is performed with a similar operation PROPAGATION_REQUIRED
a map to learn Spring spread affairs

readOnly: read-write property transactions, whichever is true or false, true read-only, default is false
rollbackFor: rollback strategy, abnormal rollback when encountering specified. For example, the example encounters an exception to rollback
timeout (supplement): Set the timeout in seconds
isolation: Set transaction isolation level, enumerated types, a total of five kinds

Type Description
DEFAULT database using default isolation level
READ_UNCOMMITTED uncommitted read data (read will appear dirty)
data read committed READ_COMMITTED (phantom read occurs, i.e., twice before and after the read is not the same)
REPEATABLE_READ, repeatable read, appear magic read
sERIALIZABLE serialization (greater consumption of resources, generally do not use)
a thorough grasp of the Spring @transactional use Spring transaction configuration and transaction isolation levels and the spread of the Detailed
 

Published 23 original articles · won praise 10 · views 120 000 +

Guess you like

Origin blog.csdn.net/gui694278452/article/details/104378270