Spring was originally founded by Rod Johnson, and its fundamental mission is to solve the complexity of enterprise application development, namely, to simplify Java development.

Three ways to assemble beans

1.1 Through Annotations [Recommended, use Component annotations for custom classes]

Implementation: Add an annotation @Component to each Javabean and hand it over to the IOC container for management. We use the @AutoWired annotation to inject in where we need it.

Public class User implements Serializable {private int ID; private String name; private int age; private String description; }Copy the code

Note: To use annotation mode, you must first enable annotation support. Just create a configuration class in Spring and add an @ComponentScan annotation to the configuration class to scan for the annotated package. As shown in 1.2 below

1.2 By configuring classes [recommended, using classes written by others, via @bean injection]

@configuration // Indicates a Configuration class, can replace the Spring XML Configuration file, recommended! @ComponentScan(basePackages = {"com.ljy"}) // Enable annotation scanning public class MyConfigg {@bean public User getUser() throws InterruptedException {system.out.println (" Start creating user object............." ); TimeUnit.SECONDS.sleep(3); User user = new User(); user.setAge(10); User.setname (" lu Jianyou "); System.out.println(" object created successfully.........." ); return user; }}Copy the code

1.3 Assembly through XML files [Not recommended]

<bean id="user" class="com.ljy.pojo.User">
Copy the code

2. Configuration of SpringAOP

2.1 open the AOP

Turn AOP on with the following annotations on the main configuration class

@configuration // indicates that this is a Configuration class. @enableAspectJAutoProxy indicates that AOP support must be enabled. @componentScan (basePackages = {"com.ljy"}) Public class MyConfig {// Register bean@bean (name = "user") public user getUser() throws InterruptedException { return new User; }}Copy the code

2.2 Create a slice

@aspect // indicates a section @component // indicates a spring Component, must! @pointcut (value = "execution(* com.ljy.service.*.*(..)); )") private void anyMethod(){} @Before("anyMethod()") public void beforeAdvice(){ System. The out. Println (" = = = = = = = = = = = = pre notice = = = = = = = = = = = = = = = = = = = "); } @ After (anyMethod "()") public void afterAdvice () {System. Out. Println (" = = = = = = = = = = = rear notice = = = = = = = = = = = = = = = "); } @ AfterReturning (anyMethod "()") public void AfterReturning () {System. Out. Println (" = = = = = = = = = rear return notice = = = = = = = = = = = "); } @ AfterThrowing (anyMethod "()") public void AfterThrowing () {System. Out. Println (" = = = = = = = = = abnormal return notice = = = = = = = = = = = = = "); } @around ("anyMethod()") public Object Around(ProceedingJoinPoint PJP) throws Throwable {Object[] args = pjp.getArgs(); for (Object arg : args) { System.out.println(arg); } String name = pjp.getSignature().getName(); Object proceed=null; Try {// @before system.out.println (" ["+name+" method start] "); Invoke (obj,args); invoke(obj,args); Proceed */ proceed = ppJ.proceed (); // @afterreturning system.out.println (" +name+"); } catch (Exception e) {// @afterthrowing system.out.println (" +name+"); }finally{// @after system.out.println (" ["+name+" method end] "); } return proceed; }}Copy the code

There are five types of notification in the section. When are they executed? We should read the annotation name can guess it! Before a method executes, after a method executes, after a method completes normally, after a method throws an exception… There is also the most powerful type of surround notification.

@around Notification:

It integrates @before, @Afterreturing, @AfterThrowing and @After. Note that the biggest difference between this annotation and the other four is that you need to manually reflect the methods in the interface before you can execute them. In other words, @around is a dynamic proxy.

Note that there is a parameter called ProceedingJoinPoint PJP, which contains information about methods in the interface. You can obtain method information in the interface through PJP (method name, method parameters, method return value, etc.).

Pointcut expression

Expression: access modifier return value package name. Package name. Package name… Class name. Method name (parameter list)

The standard expression is: Public void com. Ljy. Service. Impl. AccountServiceImpl. SaveAccount () access modifier can omit void Com. Ljy. Service. Impl. AccountServiceImpl. SaveAccount can use wildcards () returns a value, Said any return value * com. Ljy. Service. Impl. AccountServiceImpl. SaveAccount () the package name can use wildcards, said any package. But there are a few class package, just need to write a few *. * *. *. *. *. AccountServiceImpl. SaveAccount () the package name can be used.. Represents the current package and its subpackages * *.. AccountServiceImpl. SaveAccount () the name of the class and method names * *. * can be used to implement the wildcard. *.*() Parameter list: Data type: Basic type Direct write name int Name of the reference type write package. Java.lang. String can use wildcards to represent any type, but must have arguments that can use.. It can be any parameter with or without the parameter. If the parameter has any type, it can be written as * *.. *. * (..) Actual development point expression of the writing: usually cut all the way to the business layer under the implementation class * com itheima. Service. Impl. *. * (..) 六四屠杀Copy the code

Spring transactions

Spring transactions still depend on database transactions to exist. It can be said that without database transactions, there would be no Spring transactions.

What is a transaction? A transaction is a group of operations that either succeed or fail at the same time. If something goes wrong in the middle, you need to rollback the operations that have been performed. At the database level this is a group of CRUD statements that can either succeed or fail at the same time.

Let’s review some basic information about databases.

What problems might arise when working with data in a database?

1. Dirty reads

Dirty data is read when transaction A reads data that has been modified by transaction B but has not been committed.

2. Phantom reads

When transaction A performs batch modification or query, transaction B adds A new piece of data, which just meets the conditions for transaction A to perform modification or query. At this time, after transaction A performs the modification or query, re-check and find that there is still A data has not changed! This is the phenomenon of illusory reading.

3. Do not repeat the read

Transaction A performs two consecutive read operations, and in the middle of the two operations, transaction B makes A change to the data in the two operations, resulting in the data read by transaction A is inconsistent, this is called unrepeatable read!

Some students may confuse phantom reads with unrepeatable reads, which are similar, but note that phantom reads focus on insert or DELETE in another transaction, whereas unrepeatable reads focus on update in another transaction.

What are the isolation mechanisms for databases?

1. Read unsubmitted

Add an X lock (exclusive lock) when writing data, that is, no other transaction is allowed to write data, but the read is not restricted and the read is not locked.

It can solve the problem of data loss, but it cannot solve the problem of dirty data.

2. Read Submitted

Write data with X lock (exclusive lock), read data with S lock (shared lock), and there is a convention: if a data with X lock can not add S lock; Similarly if add the S lock can’t add X lock, but a data can exist at the same time more than one S lock (because only read the data), and regulation S lock reading data, read once finish it immediately release S lock (regardless of whether or not there are many other operating follow-up, as long as it is to read the S lock data, immediately release the S lock).

Fixed dirty reads, but not “unrepeatable reads”.

3. Repeat

Change S lock (S lock) to release S lock immediately after data is read. Change S lock (S lock) to release S lock immediately after data is read, but not release S lock until transaction is ready to commit.

Fixed unrepeatable reads, but not “phantom reads”.

4. The serialization

Transactions can only be executed piece-by-piece, not concurrently.

It can solve the problems of dirty reading, unreal reading and unrepeatable reading.

3.1 Spring uses transactions

Separate programmatic and declarative transactions. In plain English, this is the difference between writing your own transactions and using annotations defined by Spring.

3.1.1 Programmatic transactions
3.1.2 Declarative transactions

It’s as simple as adding an annotation to the method.

@transactional public void methodA(){system.out.println (" this is a Transactional operation...." ); System.out.println(" Insert data... ); System.out.println(" modify data...." ); System.out.println(" Delete data...." ); }Copy the code

At this point, the business in this method is “atomic”! If an exception occurs, all operations will be rolled back.

3.2 Spring Transaction Propagation Mechanism (seven)

What is the propagation mechanism for transactions? Propagation propagation, that at least two transactions need to communicate with each other! Consider this condition:

Public void methodA(){methodA(); } @Transactional public void methodB(){ methodA(); }Copy the code

The so-called transaction propagation mechanism, that is, how is the transaction passed between multiple method calls, is the transaction recreated or using the parent method transaction? Does the rollback of the parent method have any effect on the transactions of the child method? These can be determined by the transaction propagation mechanism.

  1. PROPAGATION_REQUIRED

As the name suggests, in this case the code must run in a transaction. The mechanism is: if the outer method has a transaction, it joins the transaction, if not, it creates a new transaction.

  1. PAOPAGATION_REQUIRE_NEW [Propagation – New required]

Regardless of whether the outer method has a transaction, a new transaction is created, the original method is suspended, and the old transaction continues after the new method completes execution

  1. PAOPAGATION_SUPPORTS

If there is a transaction in the outer method, then use the outer method’s transaction, if the outer method has no transaction, then use no transaction!

  1. PAOPAGATION_NOT_SUPPORTED

If you don’t support transactions, you can’t use transactions. Spring does not turn on transactions for the current method, that is, there are no transactions.

  1. PROPAGATION_MANDATORY

A transaction must be executed, and an error is reported if the outer method does not have a transaction.

  1. PROPAGATION_NEVER【 propagate – never 】

It is never allowed to execute in transactional mode, and if a transaction exists, an error is reported.

  1. PROPAGATION_NESTED

If a transaction currently exists, it is executed within a nested transaction. If there are no transactions currently, do something similar to REQUIRED and create a new transaction to execute.

We found a rule: 1.2 ===3.4 === 5.6 are corresponding to each other, so it is convenient for us to remember.

Spring often meet test questions

1. What is the life cycle of Spring beans?

  1. instantiation
  2. Fill attribute
  3. Call the setBeanName() method of BeanNameAware.
  4. Call the setBeanFactory method of BeanFactoryAware,
  5. Call the setApplicationContext method of ApplicationContextAware
  6. Call the pre-initialization method of BeanPostProcessor
  7. Invoke the afterPropertiesSet method of InitialzingBean
  8. Invokes custom initialization methods
  9. Call the post-initialization method of BeanPostProcessor
  10. The Bean is ready to use and exists in the application context
  11. Call the DisableBean deStory method
  12. Invokes custom destruction methods.

2. What are the scopes of beans in Spring?

What are the scopes of beans in Spring?

Singleton: A unique bean instance. Beans in Spring are singletons by default.

2. Prototype: Each request creates a new bean instance.

3. Request: Each HTTP request generates a new bean that is valid only within the current HTTP Request.

Session: Each HTTP request generates a new bean that is valid only for the current HTTP session.

5. Global-session: global session scope.