I. General problems

What Spring technologies are used primarily in development?

  1. The IOC container manages the layers of components
  2. Use AOP to configure declarative transactions
  3. Integrate other frameworks

What are the advantages of Spring?

  • Lightweight: Spring is definitely lightweight in terms of size and transparency. The base version of the Spring framework is only about 2MB.
  • Inversion of Control (IOC) : Spring uses inversion of control technology to achieve loose coupling. Dependencies are injected into objects rather than creating or finding dependent objects.
  • Aspect Oriented Programming (AOP) : Spring supports aspect oriented programming while separating the application’s business logic from the system’s services.
  • Container: Spring contains and manages the configuration and life cycle of application objects.
  • MVC Framework: Spring’s Web framework is a well-designed WEB MVC framework that nicely replaces some Web frameworks.
  • Transaction Management: Spring provides a unified transaction management interface for down-to-local business up to global business (JAT).
  • Exception Handling: Spring provides a convenient API for turning technology-specific exceptions (thrown by JDBC, Hibernate, or JDO) into consistent, Unchecked exceptions.

Spring modules

spring overview

Briefly describe AOP and IOC concepts

  • AOP: Aspect Oriented Program, Aspect Oriented programming; Filter(Filter) is also a kind of AOP. AOP is a new methodology, is the traditional OOP(Object-OrientedProgramming, object-oriented programming) supplement. AOP’s primary programming object is aspects, which modularize crosscutting concerns. This can be illustrated by transactions.

  • IOC: Invert Of Control. Also known as DI(dependency injection), the idea is to reverse the direction of resource acquisition. Traditional resource lookup requires a component to make a request to the container to find resources. In response, the container duly returns the resource. With IOC, the container actively pushes resources to the components it manages. All the components have to do is choose an appropriate way to receive the resources. This behavior is also known as the passive form of lookup

Dependency injection

IoC is a design concept that hands over Control of manually created objects in programs to the Spring framework. IoC is also used in other languages, not specific to Spring. IoC container is the carrier used by Spring to implement IoC. IoC container is actually a Map (key, value), which stores various objects.

The interdependencies between objects are managed by the IoC container and the object injection is completed by the IoC container. This greatly simplifies application development and frees applications from complex dependencies. The IoC container is like a factory. When we need to create an object, all we need to do is configure the configuration file/annotations, regardless of how the object was created. In a real project, a Service class might have hundreds or even thousands of classes as its underlying class. If we need to instantiate the Service, you might have to figure out the constructors of all the underlying classes of the Service every time, which can drive people crazy. With IoC, all you need to do is configure it and then reference it where you need it, which makes your project much more maintainable and easier to develop.

What is the Spring IOC container?

At the heart of the Spring framework is the Spring container. Containers create objects, assemble them together, configure them, and manage their full life cycle. The Spring container uses dependency injection to manage the components that make up an application. The container receives instructions for instantiating, configuring, and assembling objects by reading the provided configuration metadata. This metadata can be provided through XML, Java annotations, or Java code.

container magic

What is dependency injection?

DI (Dependency Injection) is a pattern of instantiating function objects that other objects depend on without knowing which class the required function comes from at the compile stage. This requires a mechanism to activate components to provide specific functionality, so dependency injection is the basis for inversion of control. How else would the framework know which component to create if the component is not controlled by the framework?

Dependency injection can be implemented in the following three ways:

  1. Constructor injection
  2. Setter method injection (property injection)
  3. Interface injection

How many IOC containers are available in Spring?

Before the Spring IOC container reads the Bean configuration to create an instance of the Bean, it must be instantiated. Only after the container is instantiated can a Bean instance be fetched from the IOC container and used

Spring provides two types of IOC container implementations

  • BeanFactory: The basic implementation of the IOC container
  • ApplicationContext: Provides more advanced features and is a subinterface to the BeanFactory

BeanFactory is the infrastructure of the Spring framework, oriented towards Spring itself; The ApplicationContext is intended for developers using the Spring framework. Almost all applications use the ApplicationContext directly instead of the underlying BeanFactory.

The configuration file is the same regardless of how you use it.

BeanFactory is different from ApplicationContext

BeanFactoryApplicationContext lazily load it makes language explicitly provide object itself to create and manage resources object does not support internationalization support internationalization does not support based on dependency annotation support based on dependency annotations

ApplicationContext

The main implementation classes of ApplicationContext:

  • ClassPathXmlApplicationContext: from the classpath to load the configuration file
  • FileSystemXmlApplicationContext: from the file system to load the configuration file
  • ConfigurableApplicationContext extension in ApplicationContext, newly added two main methods: Refresh () and close(), giving ApplicationContext the ability to start, refresh, and close the context
  • WebApplicationContext is designed specifically for WEB applications and allows initialization to be done from a path relative to the WEB root directory
  • ApplicationContext instantiates all singleton beans when the context is initialized

javadoop.com

Get beans from the IOC container

  • Call the getBean() method of ApplicationContext

    ApplicationContext ctx = new ClassPathXmlApplicationContext(“beans.xml”); HelloWorld helloWorld = (HelloWorld) ctx.getBean(“helloWorld”); helloWorld.hello();

List some of the benefits of IoC

  • It minimizes the amount of code in your application;
  • It will make your application easy to test because it does not require any singletons or JNDI lookups in unit test cases;
  • It promotes loose coupling with minimal impact and intrusion mechanisms;
  • It supports instant instantiation and lazy loading of services

Implementation mechanism of Spring IoC

The implementation principle of IoC in Spring is factory mode plus reflection mechanism. Example:

interface Fruit { public abstract void eat(); }class Apple implements Fruit { public void eat(){ System.out.println("Apple"); }}class Orange implements Fruit { public void eat(){ System.out.println("Orange"); }}class Factory { public static Fruit getInstance(String ClassName) { Fruit f=null; try { f=(Fruit)Class.forName(ClassName).newInstance(); } catch (Exception e) { e.printStackTrace(); } return f; }}class Client { public static void main(String[] a) { Fruit f=Factory.getInstance("priv.starfish.spring.Apple"); if(f! =null){ f.eat(); }}}Copy the code

Third, Beans

What are Spring Beans?

  • They are the objects that form the backbone of a user’s application
  • Beans are managed by the Spring IoC container
  • They are instantiated, configured, assembled, and managed by the Spring IoC container
  • Beans are created based on configuration metadata provided by the user to the container

What configuration options does Spring provide?

  • The dependencies and services required to configure beans based on XML are specified in an XML-formatted configuration file. These configuration files typically contain many bean definitions and application-specific configuration options. They usually start with a bean label. Such as:

  • Annotation-based configuration Instead of using XML to describe bean assembly, you can configure beans as component classes themselves by using annotations on related class, method, or field declarations. By default, the annotation assembly is not open in the Spring container. Therefore, you need to enable it in your Spring configuration file before using it. Such as:

    context:annotation-config/

  • Java API-based configuration

Spring’s Java Configuration is implemented using @Beans and @Configuration.

The @bean annotation plays the same role as the element.

  1. The @Configuration class allows you to simply call others in the same class
  2. The @bean method defines dependencies between beans.

Such as:

@Configurationpublic class StudentConfig {    @Bean    public StudentBean myStudent() {        return new StudentBean();    }}
Copy the code

Spring Bean scope?

  • In Spring, you can set the scope of a Bean in the scope property of an element.
  • By default, Spring creates only one instance of each Bean declared in the IOC container, which can be shared across the entire IOC container: all subsequent getBean() calls and Bean references return this unique Bean instance. This scope is called a Singleton, and it is the default scope for all beans.

Beans in the Spring container fall into five categories. All scope names are self-explanatory, but to avoid confusion, let’s explain:

  1. Singleton: This scope of beans is the default. This scope ensures that no matter how many requests are received, there is only one instance of a bean in each container, and the singleton pattern is maintained by the bean Factory itself.
  2. Prototype scope as opposed to singleton scope, provides one instance for each bean request.
  3. Request: Each HTTP request creates a new bean. This applies only to the WebApplicationContext. After the request completes, the bean is invalidated and collected by the garbage collector.
  4. Session: The same HTTP Session shares a bean. Different HTTP sessions use different beans. This applies only to WebApplicationContext, and the bean is invalidated after the session expires.
  5. Global-session: the global session scope, which is only meaningful in portlet-based web applications, is no longer available in Spring5. Portlets are small Java Web plug-ins that can generate snippets of semantic code, such as HTML. They are based on portlet containers and can handle HTTP requests like servlets. However, unlike servlets, each portlet has a different session

The global scope has the same effect as session scope in the Servlet.

What is the lifecycle of the Spring Bean container?

The Spring IOC container manages the Bean life cycle, and Spring allows you to perform custom tasks at specific points in the Bean life cycle.

The lifecycle flow of the Spring Bean container is as follows:

  1. The Spring container instantiates beans based on the bean definition in the configuration;
  2. Spring uses dependency injection to populate all properties, such as the configuration defined in beans;
  3. If the bean implements the BeanNameAware interface, the factory calls setBeanName() by passing the bean ID;
  4. If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory() by passing an instance of itself;
  5. Similar to the above, if other *.aware interfaces are implemented, the corresponding methods are called;
  6. If there is any BeanPostProcessors associated with bean, call the preProcessBeforeInitialization () method;
  7. If an init method (of the init-method property) is specified for the bean, it will be called;
  8. Finally, if there is any BeanPostProcessors associated with bean, will call postProcessAfterInitialization () method;
  9. If the bean implements the DisposableBean interface, destory() will be called when the Spring container closes;
  10. If the destroy method (with the destroy-method attribute) is specified for the bean, it will be called

There are several stages that occur during bean initialization, and to interact with the container’s management of the bean’s life cycle, you can implement the InitializingBean and DisposableBean interfaces. The container calls afterPropertiesSet() on the former and destroy() on the latter to allow the bean to perform certain operations when it initializes and destroys the bean.

Instead, use @postConstruct and @Predestroy, or use init-method and destroy-method properties in XML configurations

<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>

public class ExampleBean {    public void init() {        // do some initialization work    }}
Copy the code

Is equivalent to

public class AnotherExampleBean implements InitializingBean {    public void afterPropertiesSet() {        // do some initialization work    }}
Copy the code

Spring Bean lifecycle callbacks — initialize and destroy callback methods

There are three ways to implement Bean initialization and destruction callbacks: implementing interface methods, configuring them in XML, and using annotations

  • Use annotations @postconstruct and @predestroy
  • Implement the InitializingBean and DisposableBean interfaces
  • Configure init-method and destroy-method in XML

In a bean, if multiple lifecycle callback mechanisms are configured, they are invoked from top to bottom

How do you configure beans in Spring?

Beans are configured by full class name (reflection), by factory method (static factory method & Instance factory method), and by FactoryBean

What is Spring assembly

When beans are combined together in the Spring container, it is called assembly or bean assembly, and assembly is the act of creating collaborative relationships between application objects. The Spring container needs to know what beans are required and how the container should use dependency injection to bind the beans together and assemble them.

The essence of DEPENDENCY injection is assembly, and assembly is the specific behavior of dependency injection.

Injection is the instantiation process of creating beans in the Spring container, divided into property injection (setter method) and constructor injection

What is bean autowiring?

The Spring container can automatically configure associations between collaborating Beans. This means that Spring can automatically configure the relationship between a bean and other cooperating beans by checking for < property> elements in the content of the BeanFactory.

There are five types of autowiring in the Spring framework, so let’s take a look at each

  1. No: This is the default setting of the Spring framework, where autowire is turned off and developers need to specify the autowire mode themselves

  2. ByName: This option sets dependencies based on the bean name. When an attribute is automatically assembled into a bean, the container automatically looks up a matching bean in the configuration file based on the bean name. If found, it assembles the property, and if not, an error is reported.

  3. ByType: This option sets dependencies based on the bean type. When an attribute is automatically assembled into a bean, the container automatically looks up a matching bean in the configuration file based on the bean type. If found, it assembles the property, and if not, an error is reported.

  4. Constructor: The auto-assembly of the constructor is similar to the byType pattern, but only applies to beans that have the same arguments as the constructor. If no bean of the same type as the constructor argument is found in the container, an exception will be thrown.

  5. Autodetect: Spring tries to pass first

    constructor

    Use autowage to connect, and if it doesn’t perform, Spring tries to pass

    byType

    To auto-assemble

What are the limitations of autowiring?

  • Values of primitive data types, string literals, and class literals cannot be injected using autowiring.
  • The assembly will fail if more than one bean is matched (with ambiguity) in an assembly dependency

By means of annotation configuration bean | annotation-based container configuration is what

Component scanning: Spring automatically scans, detects, and instantiates components with specific annotations from the CLASspath.

Specific components include:

  • Component: Basic annotation that identifies a spring-managed Component
  • Respository: Identifies persistence layer components
  • @service: Identifies Service layer (business layer) components
  • Controller: Identifies presentation layer components

For scanned components, Spring has a default naming strategy: use unqualified class names, with the first letter lowercase. The name of the component can also be identified in annotations by the value attribute value.

When specific annotations are used on component classes, you also need to declare context: Component-scan in the Spring configuration file: context:component-scan:

  • The base-package attribute specifies a base class package to scan, and the Spring container will scan all classes in this base class package and its subpackages
  • When multiple packets need to be scanned, they can be separated by commas
  • If you only want to scan specific classes instead of all classes in the base package, you can filter specific classes using the Resource-pattern attribute, as shown in the following example:

How do I start notes in Spring

Solution of assembly?

By default, the annotation assembly is not open in the Spring container. Therefore, to use annotation-based assembly, we must enable it in the Spring configuration file by configuring the <context: annotation-config /> element.

Four, AOP

Describe Spring AOP?

Have you ever used Spring AOP? What is it for? How might it be used?

What is AOP?

AOP(aspect-oriented Programming) is a new methodology, which is a supplement to traditional OOP(Object-oriented Programming). In OOP, we use classes as our base unit, whereas in AOP, the base unit is aspects

AOP’s primary programming object is aspects

When applying AOP programming, you still need to define common functionality, but you can clearly define where and how this functionality is applied, and you don’t have to modify the affected classes. In this way crosscutting concerns are modularized into specific objects (facets).

The benefits of AOP:

  • Everything logic in one location, code is not scattered, easy to maintain and upgrade
  • The business module is more concise and contains only the core business code

AOP terminology

  • Aspect: Crosscutting concerns (functions that span multiple modules of an application), special objects that are modularized
  • Joinpoint: a specific point in the execution of a program, such as before or after a class method is called, or after a method throws an exception. At this point we can insert an AOP aspect, which is actually where the application executes Spring AOP

  • Advice: Advice is an action to be taken before or after a method executes. It is actually a piece of code that is triggered by the SpringAOP framework during program execution. Spring facets can apply five types of notifications:

  • Before: Pre-notification, called before a method is executed

  • After: Notification called after method execution, whether or not the method was successful

  • After-returning: notification that is executed only after a method has successfully completed

  • After-throwing: Notification executed when a method throws an exception and exits

  • Around: Notification of calls before and after method execution

  • Target: A notified object, usually a proxy object, also known as an advice object

  • Proxy: Object created after notification is applied to the target object

  • Pointcuts: Each class has multiple join points, points in time during the execution of a program, such as the execution of a method or the handling of an exception. AOP locates specific join points through pointcuts. Analogy: Join points correspond to records in a database, and cut points correspond to query conditions. Point of contact and the connection is not a one-to-one relationship, a tangent point matching multiple join points, cutting through the org. Springframework. Aop) Pointcut interface is described, it USES the classes and methods as a condition of the join query

  • Introduction: Introduction allows you to add new methods or attributes to an existing class

  • Weaving: Weaving is the process of applying cuts to target objects and creating new proxy objects

Spring AOP

  • AspectJ: ** The most complete and popular AOP framework in the Java community
  • In Spring2.0 and above, you can use aspectj-based annotations or xml-based configuration AOP

Enable AspectJ annotation support in Spring

  • To use AspectJ annotations in Spring applications, you must include the AspectJ class libraries in your classpath: aopalliance.jar, aspectj.weaver. Jar, and Spring-Aspects
  • Add aop Schema to the root element.
  • To enable AspectJ annotation support in the Spring IOC container, simply define an empty XML element AOP: AspectJ-AutoProxy in the Bean configuration file
  • When the Spring IOC container detects the AOP: AspectJ-AutoProxy element in the Bean configuration file, proxies are automatically created for beans that match the AspectJ aspect.

Have write: what kind of notice (Advice) | use AspectJ annotation declaration section

  • To declare an AspectJ aspect in Spring, you simply declare the aspect as a Bean instance in the IOC container. After the AspectJ facets are initialized in the Spring IOC container, the Spring IOC container creates proxies for beans that match the AspectJ facets.

  • In AspectJ annotations, an Aspect is just a Java class with the @Aspect annotation.

  • Notifications are simple Java methods that are annotated with some kind of annotation.

  • AspectJ supports five types of notification annotations:

  • @before: Pre-notification, executed Before method execution

  • @after: post-notification, executed After method execution

  • AfterRunning: Returns the notification, executed after the method returns the result

  • AfterThrowing: an exception notification after a method throws an exception

  • @around: Circular notification, executed Around a method

What are the implementations of AOP?

The technologies for implementing AOP fall into two main categories:

  • Static proxy – refers to compilation using commands provided by the AOP framework so that AOP proxy classes can be generated at compile time, hence also called compile-time enhancement;

  • Compile-time weaving (special compiler implementation)

  • Class load-time weaving (special class loader implementation).

  • Dynamic proxy – Generates AOP dynamic proxy classes “temporarily” in memory at run time and is therefore also known as runtime enhancement.

  • JDK dynamic proxy

  • CGLIB

What are the different AOP implementations

What is the difference between Spring AOP and AspectJ AOP?

  • Spring AOP is implemented based on dynamic proxies, while AspectJ is implemented based on static proxies.
  • Spring AOP supports only method-level pointcuts; Full AOP support is provided, and it also supports property-level pointcuts.

5. Data access

Spring’s support for JDBC

JdbcTemplate profile

  • To make JDBC easier to use, Spring defines an abstraction layer on top of the JDBC API to build a JDBC access framework
  • The JDBCTemplate, the heart of the Spring JDBC framework, is designed to provide template methods for different types of JDBC operations. Each template method has control over the entire process and allows you to override specific tasks in the process. In this way, the database access effort can be minimized while preserving as much flexibility as possible.

Which ORM frameworks Spring supports

Hibernate, iBatis, JPA, JDO, OJB

Six, transaction

Transaction management in Spring

As an enterprise-level application framework, Spring defines an abstraction layer on top of different transaction management apis, and application developers can use Spring’s transaction management mechanisms without having to understand the underlying transaction management apis

Spring supports both programmatic and declarative transaction management

  • Programmatic transaction management: Transaction management code is embedded in the business method to control transaction commit and rollback. When programmatic transaction management, additional transaction management code must be included in each transaction operation. It is hard coded

  • Declarative transaction management: In most cases it works better than programmatic transaction management. It separates transaction management code from business methods and implements transaction management declaratively. Transaction management, as a crosscutting concern, can be modularized with an AOP approach. Spring supports declarative transaction management through the Spring AOP framework. There are two types of declarative transactions:

  • Declarative TRANSACTIONS based on XML

  • Annotation-based declarative transactions

Transaction manager

Spring does not manage transactions directly, but provides a variety of transaction managers that delegate transaction management responsibilities to transactions of the relevant platform frameworks provided by persistence mechanisms such as Hibernate or JTA.

The Spring transaction manager interface is org. Springframework. Transaction. The PlatformTransactionManager, through the interface, Spring provides transaction managers for each platform such as JDBC, Hibernate, etc., but the implementation is up to each platform.

Different implementations of the transaction manager in Spring

The transaction manager is declared in the Spring IOC container as a plain Bean

  • In the application only needs to deal with a data source, and through JDBC access org. Springframework). The JDBC datasource. DataSourceTransactionManager

  • Use JTA on JavaEE application server (Java Transaction API) for Transaction management org. Springframework. Transaction. The JTA. JtaTransactionManager

  • Access database using Hibernate framework org. Springframework. Orm. Hibernate3. HibernateTransactionManager

The transaction manager is declared in the Spring IOC container as a plain Bean

Manage transactions declaratively with transaction notifications

  • Transaction management is a crosscutting concern
  • To enable declarative transaction management in Spring 2.x, transaction notifications can be declared using the TX: Advice element defined in TX Schema, which must be added to the root element beforehand
  • Once you have declared transaction advice, you need to associate it with a pointcut. Because transactional advice is declared outside of the AOP: Config element, it cannot be directly associated with a pointcut, so you must declare an enhancer advice in the AOP: Config element to associate it with a pointcut.
  • Since Spring AOP is proxy-based, only public methods can be enhanced. Therefore, only public methods can be used for transaction management with Spring AOP.

Manage transactions declaratively with the @Transactional annotation

  • In addition to declaring transactions in Bean configuration files with pointcuts, advice, and enhancers, Spring also allows you to annotate Transactional methods simply with the @Transactional annotation
  • To define a method as Transactional, you can add the @Transactional annotation to your method. According to Spring AOP’s proxy-based mechanism, only public methods can be annotated.
  • You can add the @Transactional annotation at the method or class level. When this annotation is applied to a class, all public methods in that class are defined to support transaction processing
  • Simply enable the TX: Annotation-driven element in the Bean configuration file and specify a transaction manager for it
  • If the name of the transaction handler is transactionManager, you can omit the transaction-Manager attribute in the TX: Annotation-driven element, which automatically detects the transaction handler with that name

Transaction propagation attribute

  • When a transaction method is called by another transaction method, you must specify how the transaction should propagate. For example, a method may continue to run in an existing transaction, or it may start a new transaction and run in its own transaction
  • The propagation behavior of a transaction can be specified by propagation properties, and Spring defines seven types of propagation behavior:

PROPAGATION_MANDATORY Indicates that the method must run in a transaction. If no transaction is currently occurring, an exception is thrown, PROPAGATION_NESTED indicating that the method should run in a nested transaction if a transaction is currently in progress. Nested transactions can be committed or rolled back independently of encapsulated transactions. If the encapsulated transaction does not exist, the behavior is like PROPAGATION_REQUIRES. PROPAGATION_NEVER indicates that the current method should not run in a transaction. If a transaction is in progress, an exception is thrown. PROPAGATION_NOT_SUPPORTED means that the method should not run in a transaction. If an existing transaction is in progress, it will be suspended while the method is running. PROPAGATION_SUPPORTS means that the current method does not need a transactional context, but it can run in a transaction if one is already running. PROPAGATION_REQUIRES_NEW indicates that the current method must run in its own transaction. A new transaction will be started and, if there is an existing transaction running, will be suspended while the method is running. PROPAGATION_REQUIRES indicates that the current method must run in a transaction. If an existing transaction is in progress, the method will run in that transaction, otherwise a new transaction will be started.

The transaction isolation level supported by Spring

Isolation Level Meaning ISOLATION_DEFAULT Uses the default isolation level of the back-end database. ISOLATION_READ_UNCOMMITTED allows changes that have not yet been committed to be read. May result in dirty, phantom, or unrepeatable reads. ISOLATION_READ_COMMITTED allows reading from already committed concurrent transactions. Dirty reads are prevented, but phantom and non-repeatable reads may still occur. Multiple reads of ISOLATION_REPEATABLE_READ of the same field give consistent results, unless the data is changed by the current transaction itself. Dirty and unrepeatable reads are prevented, but phantom reads may still occur. ISOLATION_SERIALIZABLE is fully subject to the ISOLATION level of ACID, ensuring that no dirty, unrepeatable and phantom reads occur. This is also the slowest of all isolation levels, as it is typically done by fully locking the data tables involved in the current transaction.

The isolation level of transactions is supported by the underlying database engine, not by the application or framework;

Oracle supports two transaction isolation levels and Mysql supports four transaction isolation levels.

Sets the isolated transaction property

When you use the @Transactional annotation to declaratively manage transactions, you can set the isolation level in the isolation attribute of @Transactional

In Spring transaction notifications, you can specify the isolation level in the TX: Method element

Set rollback transaction properties

  • By default, only unchecked exceptions (of the RuntimeException and Error types) cause the transaction to roll back, not checked exceptions.

  • The rollback rules for transactions are defined by the @Transactional annotation’s rollbackFor and noRollbackFor properties, which are declared of type Class[] and can therefore be assigned multiple exception classes.

  • RollbackFor: must be rolled back when encountered

  • NoRollbackFor: A group of exception classes that must not be rolled back when encountered

Timeout and read-only properties

  • Because transactions can acquire locks on rows and tables, long transactions consume resources and have an impact on overall performance
  • If a transaction only reads data but does not modify it, the database engine can optimize the transaction
  • Timeout transaction attribute: How long a transaction can be held before forced rollback, which prevents long running transactions from hogging resources
  • Read-only transaction property: Indicates that the transaction reads data but does not update data, which helps the database engine optimize the transaction

Set timeout and read-only transaction properties

  • Timeout and read-only properties can be defined in the @Transactional annotation, and the timeout property is measured in seconds

List examples of two ways:

@Transactional(propagation = Propagation.NESTED, timeout = 1000, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class) <tx:advice id="txAdvice" transaction-manager="txManager"> <! -- the transactional semantics... --> <tx:attributes> <! -- all methods starting with 'get' are read-only --> <tx:method name="get*" read-only="true" propagation="REQUIRES_NEW" isolation="READ_COMMITTED" timeout="30" no-rollback-for="java.lang.ArithmeticException"/> <! -- other methods use the default transaction settings (see below) --> <tx:method name="*"/> </tx:attributes> </tx:advice> <! -- ensure that the above transactional advice runs for any execution of an operation defined by the FooService interface  --> <aop:config> <aop:pointcut id="fooServiceOperation" expression="execution(* x.y.service.FooService.*(..) )"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceOperation"/> </aop:config>Copy the code

Seven, the MVC

What is the use of the Spring MVC framework?

The Spring Web MVC framework provides a model-View-controller architecture and ready-to-use components for developing flexible and loosely coupled Web applications. The MVC pattern helps separate different aspects of an application, such as input logic, business logic, and UI logic, while providing loose coupling between all these elements.

Advantages of Spring MVC

  • Support for a variety of view technologies, not just JSPS
  • Integration with the Spring framework (such as IoC container, AOP, and so on)
  • Clear role assignment: front-end controller (dispatcherServlet), request-to-processor mapping (handlerMapping), processor adapter (HandlerAdapter), ViewResolver (ViewResolver)
  • Supports mapping strategies for various requested resources

Of the process of Spring MVC | DispatcherServlet description

The DispatcherServlet is at the heart of the Spring MVC framework, coordinating and organizing different components to complete request processing and return responses

SpringMVC handles request processes:

  1. If a request matches the DispatcherServlet’s request mapping path (specified in web.xml), the Web container forwards the request to DispatcherServlet for processing
  2. After receiving the request, the DispatcherServlet finds the Handler of the request based on the request information (including URL, HTTP method, request header, request parameters, and Cookie) and the configuration of HandlerMapping. Think of HandlerMapping as a routing controller and the Handler as the target host
  3. When the DispatcherServlet obtains the Handler corresponding to the current request based on the HandlerMapping, it encapsulates the Handler through the HandlerAdapter and invokes the Handler using the unified adapter interface
  4. After the processor completes processing the business logic, it returns a ModelAndView to the DispatcherServlet containing the view logic name and model data information
  5. The DispatcherServlet uses ViewResoler to resolve the logical view name to the real view object
  6. Once you have the real View object View, the DispatcherServlet uses this View to render the View of the model data in the ModelAndView

Is Spring’s Controller a singleton? Is Controller thread-safe in multithreading?

Controllers are singletons by default; do not use non-static member variables, otherwise data logic will be messed up. Singletons are not thread-safe because of them

@Controller//@Scope("prototype")public class ScopeTestController {    private int num = 0;    @RequestMapping("/testScope")    public void testScope() {        System.out.println(++num);    }    @RequestMapping("/testScope2")    public void testScope2() {        System.out.println(++num);    }}
Copy the code

We first go to http://localhost:8080/testScope, the answer is 1; Then we visit http://localhost:8080/testScope2 again, the answer is 2.

@Scope(“prototype”)

We are still first visit http://localhost:8080/testScope, the answer is 1; Then we could visit http://localhost:8080/testScope2, the answer is 1.

Singletons are unsafe and lead to repeated use of attributes.

The solution

  1. Do not define member variables in controller
  2. In case you have to define a non-static member variable, use the @scope (” prototype “) annotation to set it to multi-example mode.
  3. Use the ThreadLocal variable in the Controller

Eight, annotations,

What is the Java-based Spring annotation configuration? Give some examples of annotations

Java-based configuration allows you to do most of your Spring configuration with the help of a few Java annotations instead of XML files.

The @Configuration annotation, for example, is used to mark the definition of a class that can be used as a bean by the Spring IOC container.

Another example is the @bean annotation, which indicates that this method will return an object registered as a Bean in the Spring application context.

@Configurationpublic class StudentConfig {    @Bean    public StudentBean myStudent() {        return new StudentBean();    }}
Copy the code

How to start annotation assembly?

Annotation assembly is not turned on by default. To use annotation assembly, we must configure the Context :annotation-config/ element in the Spring configuration file.

Spring MVC

@Controller

In SpringMVC, the Controller Controller is responsible for handling the requests distributed by DispatcherServlet. It encapsulates the data requested by the user into a Model after being processed by the business processing layer, and then returns the Model to the corresponding View for display. In SpringMVC you just use @Controller to mark a class as Controller, and then use @requestMapping and @RequestParam annotations to define the mapping between URL requests and Controller methods. So the Controller can be accessed by the outside world.

@RequestMapping

RequestMapping is an annotation to handle request address mapping, which can be used on a class or method

@RequestMapping

A variant of the HTTP-based method introduced after the Spring Framework 4.3

  • @GetMapping
  • @PostMapping
  • @PutMapping
  • @DeleteMapping
  • @PatchMapping

@PathVariable

Used to map the template variables in the request URL to the parameters of the functional processing method by taking the variables in the URI template as parameters

@RequestParam

Use @requestParam to bind the request parameter values, and use @RequestParam in the handler method entry to pass the request parameters to the request method

  • Value: indicates the parameter name
  • Required: Whether it is required. The default value is true, indicating that the request parameter must contain the corresponding parameter. If no parameter exists, an exception will be thrown

@RequestBody

RequestBody indicates that the method parameter should be bound to the value of the HTTP RequestBody

@ResponseBody

@responseBody indicates that the result of this method is written directly to the HTTP Response Body

If @requestMapping is used to obtain data asynchronously, the return value is usually parsed as a jump path. If @responseBody is added to the return value, it is directly written into the HTTP Responsebody instead of being parsed as a jump path. So if you get json data asynchronously, and you add @responseBody, it will return json data directly.

@ the Resource and the @autowired

@ the Resource and the @autowired are doing bean injection is used when, in fact the @ the Resource is not Spring annotations, it’s bag is javax.mail annotation. The Resource, you need to import, but Spring supports the annotation of injection.

  • Common: Both can be written on fields and setter methods. If you write both on the field, then you don’t need to write setter methods anymore.

  • The difference between

  • The @autowired annotation is provided for Spring. The @autowired annotation assembles dependent objects byType (byType). By default, it requires that dependent objects must exist, and if null values are allowed, it can be set to false. If we want to use assembly byName (byName), we can use it in conjunction with the @qualifier annotation

  • @ the Resource by default in accordance with the ByName automatic injection, provided by J2EE, you need to import the package javax.mail. The annotation. The Resource. The @Resource has two important attributes: name and type, and Spring resolves the @Resource annotation’s name attribute to the bean’s name, and the Type attribute to the bean’s type. So, if the name attribute is used, the byName auto-injection policy is used, and if the Type attribute is used, the byType auto-injection policy is used. If neither name nor type attributes are specified, the byName auto-injection policy is used through reflection.

@ModelAttribute

After the annotation is annotated by a method input, the object of the input is placed in the data model

@SessionAttribute

A property in the model is temporarily stored in HttpSession so that the property can be shared between multiple requests

@CookieValue

The @cookievalue can bind a Cookie value to a handler input parameter

@RequestHeader

The RequestHeader contains several attributes that the server can use to get information about the client. You can bind the attribute values in the RequestHeader to the input parameters of the processing method by using @requestheader

What is the difference between @Component, @Controller, @repository, and @service?

  • @Component: Marks Java classes as beans. It is a common stereotype for any Spring management component. Spring’s component scanning mechanism can pick them up and pull them into the application environment
  • Controller: Mark a class as a Spring Web MVC Controller. Beans labeled with it are automatically imported into the IoC container
  • @service: This annotation is a specialization of the component annotation. It does not provide any additional behavior for the @Component annotation. You can use @Service instead of @Component in the Service layer class because it specifies intents in a better way
  • @Repository: This annotation is a specialization of the @Component annotation with similar utility and functionality. It provides additional benefits for daOs. It imports the DAO into the IoC container and makes unchecked exceptions eligible for translation into Spring DataAccessException.

@required What are annotations for

This annotation indicates that the bean’s property must be set in the configuration, through a bean definition of explicit attribute values or by automatic assembly, if @ Required annotations bean attribute is not set, the container will throw BeanInitializationException. Example:

public class Employee {    private String name;    @Required    public void setName(String name){        this.name=name;    }    public string getName(){        return name;    }}
Copy the code

What does the @autowired annotation do

By default, @AutoWired assembles injection by type, which by default requires that the dependent object must exist (you can set its required property to false). The @AutoWired annotation provides more fine-grained control over where and how autoassembly is done. It is used the same way as @required to modify setter methods, constructors, properties, or PN methods with arbitrary names and/or multiple parameters.

public class Employee {    private String name;    @Autowired    public void setName(String name) {        this.name=name;    }    public string getName(){        return name;    }}
Copy the code

The difference between @Autowired and @Resource

Purpose: For bean injection

  • The @autowired, belongs to the Spring annotations, org. Springframework. Beans. Factory. The annotation. Autowired
  • @ the Resource, do not belong to the Spring annotations, JDK1.6 supports annotation, javax.mail. The annotation. The Resource

Common: Both used to assemble beans. On a field, or on a setter method

Difference: @autoWired assembles by type by default. The dependent object must exist. To allow null values, you can either set its required attribute to false @autowired (Required =false) or use name assembly with the @qualifier annotation

By default, @Resource assemples injection by name, and only by type if no bean matching the name can be found

What are the @qualifier annotations for

When you create multiple beans of the same type and want to assemble only one of them using attributes, you can use the @Qualifier annotation and @AutoWired to disambiguously specify which exact bean should be assembled.

What are the @requestMapping annotations for?

The @RequestMapping annotation is used to map a specific HTTP request method to a specific class/method in the controller that will handle the corresponding request. This annotation applies at two levels:

  • Class level: URL of the mapping request
  • Method level: mapping URLS and HTTP request methods

Ix. Other issues

What design patterns are used in the Spring framework?

  • Factory Design pattern: Spring uses the factory pattern to create bean objects from the BeanFactory, ApplicationContext.
  • Proxy design pattern: Implementation of Spring AOP functionality.
  • Singleton design pattern: Beans in Spring are singleton by default.
  • Template method pattern: Spring’s jdbcTemplate, hibernateTemplate, and other classes that end in Template for database operations use the Template pattern.
  • Wrapper design pattern: Our project needs to connect to multiple databases, and different customers need to access different databases on each visit. This pattern allows us to dynamically switch between different data sources based on customer needs.
  • Observer Pattern: The Spring event-driven model is a classic application of the Observer pattern.
  • Adapter pattern: The adapter pattern is used in Spring AOP enhancements or Advice, and is used in Spring MVC to adapt controllers.

The last

Thank you for reading here, the article is inadequate, welcome to point out; If you think it’s good, give me a thumbs up.

Also welcome to pay attention to my public number: programmer Maidong, Maidong will share Java related technical articles or industry information every day, welcome to pay attention to and forward the article!