Spring Core Demo

Spring Core Demo

Spring Spring Framework for short, is the most popular Java development framework, second only to Java API, and even more popular in recent years, micro-services framework SpringBoot, also based on the realization of Spring, was born SpringBoot is to allow developers to more easily use Spring, thus Spring position in the Java system can be described as second to none.
Of course, if you want to speak to all the features of Spring crystal clear, far from being able to do one or two articles, but fortunately, Spring biography can be easily searched, then we talk about this major the core aim is to share knowledge in the Spring and common interview questions to you, I want to be able to help.

Spring Introduction

Spring is an open source framework, in order to solve the complexity of enterprise application development created, Spring concept was born in 2002, in 2003 released the first version of the Spring Framework 0.9. Spring update together look at the following characteristics of the various versions of its development and change it.

Spring 1.x

This version is mainly to solve the complexity of enterprise application development and created the classic architecture of J2EE applications are then layered architecture: presentation layer, business layer, persistence layer, the most popular combination is the SSH (Struts, Spring, Hibernate) .
Spring 1.x only supports XML-based configuration, to ensure that the user code does not rely on Spring, which mainly contains the following modules: aop, beans, ejb, jdbc , jndi, orm, transation, validation, web and so on.

Spring 2.x

Spring 2.x changes is not great, mainly to increase the number of new modules on the basis of the Spring 1.x, such as ehcache, jms, jmx, scripting, stereotype and so on.

Spring 3.x

Spring 3.x began more than support XML configuration also extends the Java-based configuration class, also increased the Expression, Instructment, Tomcat, oxm and other components, while the original Web subdivided into: Portlet, Servlet.

Spring 4.x

Spring 4.x expanded Groovy, Messaging, WebMvc, Tiles2, WebSocket and other functional components, while also adapting the Spring Java version, full support for Java 8.0, Lambda expressions. With the RESTful architectural style has been adopted by more and more users, Spring 4.x also provides new features RestController notes and so on.

Spring 5.x

Spring 5.x followed by iterative updating Java related technologies, constantly adapting new version of Java, while continuing to optimize the reconstruction of their core framework code, functional support, reactive programming model.

Spring core

Spring core includes the following three aspects:

  • Inversion of Control (Ioc,)
  • Dependency injection (DI)
  • Aspect Oriented Programming (AOP)

The following are the properties of its look.

Inversion of Control (IoC)

Inversion of control (Inversion of Control, IoC), as the name suggests is the so-called inversion of control rights to the created object to the control frame, without the need to artificially created, thus achieving a pluggable interface programming, effective code reduce coupling, it reduces the cost of maintenance and expansion.
For example, you go to a place no longer travel with their own personally ordered A hotel or B Hotels to worry about, just need to stay need to tell it to a hosting platform, the hosting platform will help you order a cheap and comfortable hotels, and this hotel help you order behavior can be called inversion of control.

Dependency injection (DI)

Dependency injection (Dependency Injection, DI), is dependent on the relationship between the components is determined by the operation of the vessel, i.e. the dynamic dependency injected from a container into the assembly. Dependency injection is not intended to bring more functionality to software systems, but to enhance component reuse frequencies, and for the system to build a flexible, scalable platform. Via dependency injection mechanism, requires only a simple configuration, without any code can specify the target resources needed to complete their business logic without having to be concerned about the specific resources come from, who to achieve.

The relationship between IoC and DI

Spring IoC is an extremely important concept is the realization of IoC and DI ways and means.
Next, we look at common implementation of dependency injection What?
Dependency injection common implementation is as follows:

  1. setter injection
  2. Constructor injection
  3. Notes injection
1) setter injection

Java code:

public class UserController {
    // 注入 UserService 对象
    private UserService userService;
    public void setUserService(UserService userService){
        this.userService = userService;
    }
}

XML located:

\<bean name="userController" class="com.learning.controller.UserController"\>  
    \<!-- 依赖注入 --\>  
    \<property name="userService" ref="userService"\>\</property\>  
\</bean\>  
\<bean name="userService" class="com.learning.dao.impl.UserServiceImpl"\>\</bean\>

Bean common attributes label instructions:

  • id: From the instance of the object name, the object can be instantiated according to our configuration value id, the name can be named principle id attribute, but can contain any special symbols;
  • class: create a full path to where the object of the class;
  • name: Function and id attributes, but now generally do not; the difference is that with id: name attribute value can contain a special symbol, but id not;
  • scope: The most commonly used are two values: Singleton: Singleton, the entire application, creates only one instance of the bean; Prototype: prototype model, each injection will create a new instance of the bean, Spring default singleton mode.
2) Constructor injection

Java code:

public class UserController {
    private UserService userService;
    public UserController(UserService userService){
        this.userService = userService;
    }
}

XML located:

\<bean name="userController" class="com.learning.controller.UserController"\>  
    \<!-- 依赖注入 --\>  
    \<constructor-arg ref="userService"\>\</constructor-arg\>  
\</bean\>  
\<bean name="userService" class="com.learning.dao.impl.UserServiceImpl"\>\</bean\>  
3) Notes injection
@Controller
public class UserController {
    // 使用注解自动注入
    @Autowired()
    private UserService userService;
    // do something
}
// 创建依赖对象
@Service
public class UserService {
   // do something 
}

Create dependent objects of common annotation: @ Component, @ Controller, @ Service, @ Repository.

Summary : It can be seen as annotations than traditional XML (setter and constructor injection) is injected to achieve a more convenient, but also notes the official way of pushing the best use of dependency injection.

Aspect Oriented Programming (AOP)

Aspect Oriented Programming (Aspect Oriented Programming, AOP), it is like the system in accordance with the functional classification, each category is a "cut", we then formulate corresponding to different facets of rules, similar to the development model is called aspect-oriented programming.

AOP usage scenarios
  • Logging system
  • Security and unity efficacy
AOP advantage
  • Focus on a certain type of problem, easy maintenance
  • Logic clearer
  • Reduce the coupling between modules
AOP concepts
  • Join point: the point of attachment, a certain point during program execution, such as performing an abnormal point method or process time in Spring AOP, represents the point of attachment is always performing the method.
  • Advice: notification that is divided into front notification method executed after execution notification method, notification surround. Many AOP frame (including the Spring) are modeled as a notification interceptor, maintaining a series connection point around the interceptor (interceptor chain form), a method of enhancing the point of attachment.
  • Pointcut: cut point, matching connection point (Join point) expression, AOP is the core, and as a starting point AspectJ Spring expression language used by default.
  • Aspect: section, it is a point of interest across a plurality of modular type, which is a notification (the Advice) and the tangential point (Pointcut) together abstract, it defines a tangent point (Pointcut) used to match the connection point (Join point), which is required for those who need to intercept method to be defined.
  • Target object: target object, the object to be notified of one or more aspects (Aspect), which is to be carried out AOP intercept method to enhance objects (using notifications), also known objects to be notified. Since AOP proxy in which the use of run-time, and thus the target object has been the object being proxied.
  • AOP proxy: AOP agent, in order to achieve cut (Aspect) function using AOP framework to create an object, refers to an AOP proxy Spring framework which is itself dynamic proxy JDK dynamic proxy or CGLIB implemented.
  • Weaving: linking aspects added to the object, and create a proxy object of the process.
  • Advisor: a Advisor equivalent of a small section, except that it is only a notification (Advice), Advisor in the transaction manager will often encounter inside.
AOP code implementation

AOP examples we have to drive a car, for example, to drive the complete process is this: The tour launch vehicle and the surrounding circumstances → → → car → turn off lock your car.

Of course, our main purpose is to "drive", but before and after driving the car was finished, we have to do some other work, these "other" work can be understood as AOP programming.

1) create classes and methods
package com.learning.aop;
import org.springframework.stereotype.Component;

@Component("person")
public class Person {
    public void drive() {
        System.out.println("开车");
    }
}
2) create AOP interceptors
package com.learning.aop;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class CarAop {
    @Before("execution(\* com.learning.aop.Person.drive())")
    public void before() {
        System.out.println("巡视车体及周围情况");
        System.out.println("发动");
    }
    @After("execution(\* com.learning.aop.Person.drive())")
    public void after() {
        System.out.println("熄火");
        System.out.println("锁车");
    }
}
3) XML configuration package scan path injection
\<?xml version="1.0" encoding="UTF-8"?\>
\<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"\>
    \<context:component-scan base-package="com.learning"/\>
    \<aop:aspectj-autoproxy/\>
\</beans\>
4) Create a test class
package com.learning.aop;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class PersonTest {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        Person landlord = context.getBean("person", Person.class);
        landlord.drive();
    }
}

Run the test code, execution results are as follows:

Inspection body and the surrounding circumstances

launch

Drive a car

Flameout

Lock your car

AspectJ annotation Description:
  • @Before - pre-notification, called before the connection point method;
  • @Around - around advice, it will overwrite the existing method, but allows you to call the original method through reflection;
  • @After - Rear notification method is called after a connection point;
  • @AfterReturning - Returns the notification, and the method performed at the connection point after the call returns normally, the point of attachment method requires no exception occurs during execution;
  • @AfterThrowing - exception notification, exception invoked when the attachment point method.

Related interview questions

What is the role 1. @ Value annotation is?

A: You can read the properties profile based @Value comment, use the following:

@Value("#{configProperties['jdbc.username']}")

private String userName;

The above is the configuration read jdbc.username configProperties.

2.Spring notification types are there?

A: Spring notification types There are five kinds: pre-notice, notice surround, rear, throws advice, the final notification.

  • Pre-notification (Before advice): Advice to be executed before the target method is executed. Advice to be executed before a join point (join point), but which does not prevent the execution before the connection point (unless it throws an exception).
  • Around advice (Around Advice): can an enforcement notice additional code before and after the execution of the target method, you can also choose whether to continue to perform the join point or return to their own return value or throwing an exception execution.
  • After returning advice (After (finally) advice): notification (either normal or exceptional return) after the target method executes (a connection point exits) execution.
  • Abnormal notice (After throwing advice): Advice to be executed when an exception is thrown exit method.
  • The final notification (After returning advice): after normal completion notification performed at a connection point (join point), e.g., a method without throwing an exception, the normal return.

3. To understand how the Spring IOC container?

A: Spring IOC is created rights object to the frame to control, without the need to artificially created, thus achieving a pluggable programming interface, effectively decouple code, reducing maintenance and expansion cost.

For example, go somewhere no longer travel with their own personally ordered A hotel or B Hotels to worry about, just need to stay need to tell it to a hosting platform, the hosting platform will help you order a cheap and comfortable hotels, and this hotel help you order behavior can be called inversion of control.

4. understand how dependent the Spring injection?

A: Dependency Injection refers to dependencies between components at runtime is determined by the container that will be injected by the container dynamic dependencies into a component. Dependency injection is not intended to bring more functionality to software systems, but to enhance component reuse frequencies, and for the system to build a flexible, scalable platform. Via dependency injection mechanism, we need only a simple configuration, without any code can specify the target resources needed to complete their business logic without having to be concerned about the specific resources come from, who to achieve.

5.IoC and DI What is the relationship?

A: IoC Spring is a very important concept, provides an object management functions, eliminating the need to create a man-made trouble, and DI is the realization of IoC ways and means.

6. @ Component and @Bean What is the difference?

A: Different objects of their role: @Component acting class, and act on an annotated @Bean.

@Component typically automatically detect by scanning the class path and fitted into the Spring container objects, such as annotations @ComponentScan scan path is defined classes fitted into Spring Bean container; @Bean annotation is told that a specific class Spring examples of when to use it when I need it to me, @ Bean custom annotation stronger than @Component notes, a lot of places we can only be registered by @Bean Bean annotation, such as when we refer to a third-party library classes required when fitted to the container Spring, can only be achieved through @Bean, such as the following example, only be achieved by @Bean Note:

public class WireThirdLibClass {
    @Bean
    public ThirdLibClass getThirdLibClass() {
        return new ThirdLibClass();
    }
}

7.Spring the scope of the bean There are several types?

A: Spring in the scope of the bean There are four types, the following list:

  • Singleton (Singleton): the entire application, create only one instance of the bean;
  • Prototype (Prototype): each injection will create a new bean instance;
  • Session (Session): each session to create a bean instance, is only valid in the Web system;
  • Request (Request): for each request to create a bean instance, is only effective in the Web system.

Spring default mode is a single embodiment.

8. What is the Spring of internal bean?

A: When bean is used only as a bean property to another, it can be declared as an internal bean, in order to define inner Bean, configuration metadata XML-based, you may be in the Spring of <property/>or <constructor-arg/>provided with elements <bean/>elements, internal bean usually anonymous, their Scope generally prototype.

9.Spring injection method What?

A: Spring injection contains the following five ways:

  • setter injection
  • Constructor injection
  • Notes injection
  • Static Factory injection
  • Examples of injection plant

The most commonly used is the first three, the official recommended a comment injection, relatively simpler, lower maintenance costs and more intuitive.

10. How to operate the database in Spring?

A: In Spring operation of the database, may be used JdbcTemplate objects provided by Spring, JdbcTemplate class provides many convenient method, such as the database data into basic data types or objects, perform custom SQL statements, provides custom data error handling, JdbcTemplate use example is as follows:

@Autowired
private JdbcTemplate jdbcTemplate;
// 新增
@GetMapping("save")
public String save(){
    String sql = "INSERT INTO USER (USER\_NAME,PASS\_WORD) VALUES ('laowang','123')";
    int rows = jdbcTemplate.update(sql);
    return "执行成功,影响" + rows + "行";
}
// 删除
@GetMapping("del")
public String del(int id){
    int rows= jdbcTemplate.update("DELETE FROM USER WHERE ID = ?",id);
    return "执行成功,影响" + rows + "行";
}
// 查询
@GetMapping("getMapById")
public Map getMapById(Integer id){
    String sql = "SELECT \* FROM USER WHERE ID = ?";
    Map map= jdbcTemplate.queryForMap(sql,id);
    return map;
}

11.Spring of JdbcTemplate objects and JDBC What is the difference?

A: Spring is a package of JdbcTemplate JDBC API provides more functionality and more convenient operation, such as JdbcTemplate have:

  • JdbcTemplate is thread-safe;
  • Examples of the operation is relatively simple, requiring only the DataSource transfer;
  • Automate the creation and release of resources;
  • Creating a JdbcTemplate, available everywhere, to avoid duplication of development.

12.Spring There are several ways to achieve affairs?

A: Spring implement the transaction in two ways: programmatic and declarative transaction transaction.
Programmatic transaction, or the TransactionTemplate PlatformTransactionManager implementation, the following sample code:

private final TransactionTemplate transactionTemplate;
public void add(User user) throws Exception{
    // Spring编码式事务,回调机制
    transactionTemplate.execute(new TransactionCallback<Object>() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            try {
                userMapper.insertSelective(user);
            } catch (Exception e) {
                // 异常,设置为回滚
                status.setRollbackOnly();
                throw e;
            }
            return null;
        }
    });
}

If there is an exception, calling status.setRollbackOnly () rolls back the transaction, otherwise doInTransaction () method is normal, normal transaction is committed.
If the method does not require return transaction control value, can be used (an abstract class that implements interface TransactionCallback) TransactionCallbackWithoutResult following sample code:

public void add(User user) throws Exception {
    // Spring编码式事务,回调机制
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            try {
                userMapper.insertSelective(user);
            } catch (Exception e) {
                // 异常,设置为回滚
                status.setRollbackOnly();
                throw e;
            }
        }
    });
}

Declarative transaction, the bottom is based on the Spring AOP, to intercept before and after implementation, and create a new transaction or join an existing transaction before the target method to begin the last goal in the method according to the situation after the implementation of submitted or back roll transactions.
Declarative transactions advantages: no programming code reduce coupling, arranged in the configuration file and add @Transactional annotation methods to achieve the objectives, the following sample code:

@Transactional
public void save() {
    User user = new User("laowang");
    userMapper.insertSelective(user);
    if (true) {
        throw new RuntimeException("异常");
    }
}

An exception is thrown, the transaction is automatically rolled back if a method execution, it will automatically commit the transaction.

13.Spring transaction isolation level What?

A: Spring injection contains the following five ways:

  • ISOLATION_DEFAULT: setting isolation level with the underlying database, database setup is what I what;
  • ISOLATIONREADUNCOMMITTED: read uncommitted, the lowest isolation level, before the uncommitted transactions, can be read by other transactions (Magic will read, dirty reads, non-repeatable read);
  • ISOLATIONREADCOMMITTED: Read Committed, after a transaction commits to be read by other transactions to (cause phantom reads, non-repeatable read), the default level of SQL server;
  • ISOLATIONREPEATABLEREAD: repeatable read, when reading the same data multiple times to ensure that its values ​​and contents of the transaction start time is the same, to prohibit read data other uncommitted transactions (cause phantom read), MySQL's default level ;
  • ISOLATION_SERIALIZABLE: serialization, the costliest most reliable isolation level, the isolation level can prevent dirty reads, non-repeatable read, phantom read.

The default value is ISOLATION_DEFAULT follow the transaction database isolation level.

14.Spring declarative transaction invalid What are the possible causes?

A: The possible reasons are as follows:

  • MySQL using MyISAM engine, MyISAM does not support transactions;
  • @Transactional use on non-public methods, @ Transactional annotation can only support public level, the affairs of other types of declaration will not take effect;
  • A method @Transactional affairs in the absence of the same class () method is called internally there is a transaction B (), then the time B () thing will not take effect. What's in Spring AOP underlying principle is to achieve?

A: The principle underlying implementation Spring AOP is the dynamic proxy. Spring AOP dynamic proxy is implemented in two ways, the interface used for carrying the JDK dynamic proxy to achieve, whereas the comparative non CGLib interface is achieved, details of the dynamic proxy may refer to the previous reflection [ and the dynamic proxy] article.

15.Spring in Bean thread-safe?

A: Spring is in default singleton Bean, Spring framework does not encapsulate processing multiple threads of a single case of Bean, Bean by default and therefore is not safe, simple security measures to ensure the Bean Bean is to set the scope of It is prototype (prototype) mode, so that every request a new Bean.

16. talk about Spring Bean in the life cycle?

A: Spring in Bean's life cycle is as follows:

  • ① Examples of Bean: For BeanFactory container, when a client requests Bean the container has not been initialized, the initialization Bean or when another has not been initialized to be injected depends, the container will call createBean instantiated. For ApplicationContext container, when after the container starts by acquiring information BeanDefinition objects, all instances of Bean;
  • ② Set object properties (dependency injection): After the object is instantiated BeanWrapper encapsulated in a subject, followed Spring dependency injection is completed in accordance with the interface information BeanDefinition setting properties provided by BeanWrapper;
  • ③ Processing Aware Interface: Spring detects whether the object implements xxxAware interface and associated injection to Example xxxAware Bean:
  • If this has been achieved BeanNameAware Bean interface calls setBeanName (String BeanId) method to achieve it, here is the transfer of Spring id value of the configuration file Bean;
  • If this has been achieved BeanFactoryAware Bean interface will call it implements setBeanFactory () method, passing the Spring plant itself;
  • If this has been achieved ApplicationContextAware Bean interface calls setApplicationContext (ApplicationContext) method, passing in the Spring context;
  • ④ BeanPostProcessor: If you want to do some processing Bean custom, you can let Bean implements BeanPostProcessor interface, it will call postProcessBeforeInitialization (Object obj, String s) method;
  • ⑤ InitializingBean with the init-method: If Bean configured init-method property in the Spring configuration file, it will automatically call the initialize method of its configuration;
  • ⑥ If the Bean implements BeanPostProcessor interface will be called postProcessAfterInitialization (Object obj, String s) method; Since this method is called at the end of Bean initialization, which can be applied to memory or cache technology;

After a few more steps to complete, Bean has been created correctly, then you can use the Bean of.

  • ⑦ DisposableBean: Bean when no longer needed, it will clean-up stage, if the Bean implements this interface DisposableBean, its implementation will call destroy () method;
  • ⑧ destroy-method: Finally, if the Bean in Spring configuration to configure the destroy-method attributes, its configuration will automatically destroy method is called.

17.Spring What are the advantages?

A: Spring has the following advantages:

  • The popular free open source framework, high stability, and low cost to solve the problem;
  • Easy integration of various excellent framework;
  • Reducing the coupling code, the IoC container provided by Spring, we can rely on the relationship between objects referred Spring controlled to avoid excessive coupling hardcoded program caused;
  • Convenient testing program, in Spring, the test becomes very simple, for example: Spring's support for Junit, you can easily comment Spring test procedures;
  • The difficulty of reducing the use of Java EE API, Spring for many difficult to use Java EE API (such as JDBC, JavaMail, remote calls, etc.) to provide a layer of packaging, simple package by Spring, so the difficulty of using these Java EE API greatly reduced .

18.Spring difference and Struts?

A: Spring and Struts differences are as follows:
the Spring characteristics are as follows:

  • GM has the ability to IOC / DI, AOP, etc., to improve the efficiency of research and development
  • In addition to supporting Web layer construction, it also provides a J2EE overall service
  • Easy to combine with other different technologies, such as Hibernate, MyBatis etc.
  • Spring interception mechanism is the method level

Struts characteristics are as follows:

  • MVC model is a process of a Web-based layer
  • Struts interception mechanism is the class level

19.Spring, what is the difference SpringBoot, SpringCloud is?

A: Their differences are as follows:

  • Spring Framework referred Spring, Spring is the basis of the entire ecology.
  • Spring Boot is a rapid development framework that allows developers to quickly build a Spring-based applications, and popular Spring modules as well as third-party modules, such as MyBatis, Hibernate and so do a good integration, only need a simple configuration to use, does not require any XML configuration file, truly out of the box, while the default data format JSON support, end the separation developed using Spring Boot before and after is also very convenient.
  • Spring Cloud is an integrated framework for distributed applications commonly used modules, allows developers to quickly implement micro-service applications. As currently very popular technology topics related to micro and services is always under discussion in various scenarios, the company's recruitment information requirements for micro-services architecture capabilities are also increasingly present.

20.Spring which are used in the design mode?

A: Spring in using design patterns as follows:

  • Factory mode: to create the bean by BeanFactory, ApplicationContext belong to factory mode;
  • Singleton, the prototype model: Create object set bean scope can be declared the Singleton (Singleton), the Prototype (prototype model);
  • Observer's mode: Spring can define what the listener, such as when ApplicationListener will notify you when an action is triggered;
  • Chain of Responsibility pattern: the implementation of AOP interceptors;
  • Strategy Mode: When you create a proxy class, if the agent is the interface using JDK dynamic proxy itself, if not an interface using CGLIB dynamic proxy.

to sum up

By this section we have a full understanding of Spring's core: IoC, DI, AOP, but also with the code shows an example of the core functions of Spring, which can be found in the Spring configuration is programmed into a Java programming notes from the previous XML, annotations Spring make programming more lightweight simplistic, this is behind us introduce SpringBoot time, it will make you more empathy. For developers, the only truly mastered the Spring, it can be regarded as a qualified engineer Java. Of course, the purpose of the study is to better applications, so now with hands-up bar.


I welcome the attention of the public number, keyword reply " the Java ", there will be a gift both hands! ! ! I wish you a successful interview ! ! !

% 97% E5% 8F% B7 % E4% BA% 8C% E7% BB% B4% E7% A0% 81.png)

Guess you like

Origin www.cnblogs.com/dailyprogrammer/p/12272773.html