Spring Point Basics

Spring Framework which are used in the design mode?

  • Factory mode: BeanFactory is the embodiment of simple factory pattern is used to create an instance of an object;
  • Singleton: Bean default singleton.
  • Agent Mode: Spring AOP function uses the JDK dynamic proxy and CGLIB bytecode generation technology;
  • Template Method: to solve the problem of code duplication. For example. RestTemplate, JmsTemplate, JpaTemplate.
  • Observer pattern: definition object dependency relationship of many of the key, when a state of the object changes, all objects that depend on it are notified braked updated, as implemented in Spring listener -ApplicationListener.

Spring provides the following five standard events:

  • Context update event (ContextRefreshedEvent): is triggered when calling the ConfigurableApplicationContext Interface refresh () method.
  • Context start event (ContextStartedEvent): When the container invokes ConfigurableApplicationContext the Start () method to start / restart the event is triggered when the container.
  • Context stop event (ContextStoppedEvent): This event is triggered when a container calls ConfigurableApplicationContext the Stop () method to stop the vessel.
  • The context of the closing event (ContextClosedEvent): This event is triggered when the ApplicationContext is closed. When the container is closed, all singleton Bean their management have been destroyed.
  • Request processing events (RequestHandledEvent): In the Web application, when the end of a http request (request) that triggered the event. If a bean implements the interface ApplicationListener, when after a ApplicationEvent was released, bean will automatically be notified.
     

BeanFactory and ApplicationContext What is the difference?
Spring BeanFactory and ApplicationContext are the two core interfaces, can be used as the Spring container. Which ApplicationContext is a subinterface of BeanFactory.

Dependencies

BeanFactory: Spring which is the bottom of the interface, including the definition of a variety of Bean, read bean configuration files, manage bean loading, instantiation, control bean life cycle, maintain dependencies between bean.

As derived BeanFactory ApplicationContext interface, in addition to providing BeanFactory has the function, but also provides a more complete framework functions:

  • Inheritance MessageSource, thus supporting internationalization.
  • Unified resource file access.
  • Provide listeners registered bean events.
  • While loading multiple profiles.
  • Loading of multiple (hierarchical) context, a context that each focused on a specific level, such as the web application layer.

Loading

BeanFactroy uses a form of lazy loading to inject Bean, that is only in use when a Bean (call getBean ()), only to load the Bean is instantiated. In this way, we can not find some of the Spring configuration problems exist. If one of Bean's attributes are not injected, after BeanFacotry load until the first call to use getBean method will throw an exception.

ApplicationContext, which is when the container starts, disposable created all of Bean. Thus, when the container starts, we can find Spring configuration errors exist, this will help to check whether the dependency property injection. After pre-loaded ApplicationContext start all single-instance Bean, by pre-loading single-instance bean, when you need to make sure, you do not have to wait, because they have been created.

With respect to basic BeanFactory, ApplicationContext only downside is take up memory space. When the application is configured more Bean, the program starts slow.

Create a way

BeanFactory often be created programmatically, ApplicationContext can declaratively create, such as the use ContextLoader.

way to register

BeanFactory and ApplicationContext support BeanPostProcessor, use BeanFactoryPostProcessor, but the difference between the two is: BeanFactory need to manually register, while the ApplicationContext is automatically registered.

What usually ApplicationContext implementation is?
FileSystemXmlApplicationContext: This container load of beans from a defined XML file, XML Bean configuration file full path name must be provided to its constructor.

ClassPathXmlApplicationContext: This container is also loaded with the definition of beans from an XML file, where you need to correctly set the classpath because the bean container will find in the classpath configuration.

WebXmlApplicationContext: This container load an XML file that defines all bean a WEB application.

Spring supports several bean explain the scope of
the Spring framework supports the following five bean scope:

  • singleton: bean only one instance of each Spring ioc container.
  • prototype: a bean definition can have multiple instances.
  • request: every http request creates a bean, this scope is only valid in the case of Spring ApplicationContext web-based.
  • session: a HTTP Session, the definition to a bean. Only valid in the case of Spring ApplicationContext web-based.
  • global-session: a global HTTP Session, the definition to a bean. Only valid in the case of Spring ApplicationContext web-based.

Note: The default scope Spring bean is Singleton. Use the prototype scope needs to think carefully, because frequently created and destroyed bean will bring significant performance overhead.

How Spring processing thread concurrency issues?
In general, only stateless Bean can only be shared in a multithreaded environment, in Spring, the vast majority Bean can be declared as singleton scope, because some Spring in Central Africa Bean thread-safe state for processing using ThreadLocal, address security thread.

ThreadLocal and thread synchronization mechanisms are made to address multiple threads access the same variable conflict. Way synchronization mechanism uses "time for space," the only variable to provide a different thread needs to acquire a lock before the visit, the thread did not get the lock you need to line up. The use of ThreadLocal way "space for time".

ThreadLocal will provide a copy of the independent variables for each thread, thereby isolating the conflict on multiple threads access the data. Because each thread has its own copy of the variable, so there is no need for the variable sync. ThreadLocal provide a thread-safe shared objects, when writing multithreaded code can be encapsulated into the unsafe variables ThreadLocal.
Spring Framework bean explain the life cycle of
the traditional Java applications, bean life cycle is very simple. Use the keyword new Java bean be instantiated, then the bean is ready for use. Once the bean is no longer used by the Java garbage collection automatically. In contrast, Spring containers in the life cycle of the bean becomes relatively more complicated. Spring bean correct understanding of the life cycle is very important, because you may want to take advantage of Spring provides extension points to customize the creation of the bean. The following figure shows a typical load bean life cycle Spring application context.

bean in the Spring container from creation to destruction through several stages, each stage how you can manage for Spring bean for customization.

As you can see, it is ready before the bean, bean plant implemented a number of start-up procedure.

We conducted a detailed description of the figure:

Spring bean to be instantiated;

Spring bean reference value and is injected into the bean corresponding attribute;

If the bean implements the interface BeanNameAware, Spring bean passes the ID to setBean-Name () method;

If the bean implements the interface BeanFactoryAware, Spring calls setBeanFactory () method, passing the BeanFactory container instance;

If the bean implements the interface ApplicationContextAware, Spring will call setApplicationContext () method will be applied where the bean reference to the context of the incoming come in;

If the bean implements BeanPostProcessor interface, Spring calls their post-ProcessBeforeInitialization () method;

If the bean implements the interface InitializingBean, Spring will call their after-PropertiesSet () method. Similarly, if the bean uses initmethod declared initialization method, which is also called;

If the bean implements BeanPostProcessor interface, Spring calls their post-ProcessAfterInitialization () method;

At this point, bean is ready, the application can be used, they will always reside in the application context, until the application context is destroyed;

If the bean implements the interface DisposableBean, Spring will call its destroy () interface method. Similarly, if the bean using the destroy-method declaration destruction method, which is also called.

Now that you know how to create and load a Spring container. But an empty container and do not have much value, before you put things, it contains nothing. For the Spring of DI (DI) benefit, we have to fit into the application object Spring container.

What is important bean life cycle approach? You can reload them?
There are two important bean life cycle approach, the first one is setup, it is called when the bean container loads. The second method is to teardown it is called when unloading a container class.

bean tag has two important properties (init-method and destroy-method). You can use them to customize their own initialization and logout methods. They also have corresponding comments (@PostConstruct and @PreDestroy).

Explain the different ways of automatic assembly, spring bean automatic assembly what way?
In the spring, the object without having to look for other objects or create their own associated with it, the responsibility of the vessel to the need for mutual collaboration object reference gives each object, using autowire to configure automatic loading mode.

There are five types of automatic assembly Spring Framework xml configuration:

no: The default mode is not the automatic assembly, the assembly is performed manually setting bean ref attribute.

byName: name of the bean by automatic assembly, the same as if a bean property of the bean to another name, to carry out automatic assembly.

byType: automatically assembled by the data type parameter.

constructor: using the constructor assembly, and the parameters are assembled by the constructor byType.

autodetect: automatic detection, if the constructor, by automatic assembly construct manner, otherwise the automatic assembly byType manner.

Use @Autowired annotation automatic assembly process like?
@Autowired annotation using automatic assembly designated bean. @Autowired required prior to use in the annotation Spring profile configuration, <context: annotation-config / >.

Spring IoC at startup, automatically load a container AutowiredAnnotationBeanPostProcessor post processor, when the container is scanned @ Autowied, @ Resource or @Inject, will automatically find the bean needs IoC container, and fitted to the object's properties. In use @Autowired, corresponding to the first type of query bean in the container:

  • If a query result is exactly, to the assembly to @Autowired bean specified transactions;
  • If the result of the query is more than one, it will be to find @Autowired by name;
  • If the result of the lookup is empty, then throws an exception. Solving method, required = false.

What are the limitations of automatic assembly have?
Automatic limitation of the assembly is:

Rewrite: You still need to use and configure to define the dependencies, which means always override the automatic assembly.

Basic data types: You can not simply attribute automatic assembly, as the basic data types, String String, and class.

Blur characteristic: automatic assembly explicit fitting accuracy is better, if possible, use the explicit assembly.

You can inject a null in the Spring and an empty string it?
can. What is the role @Autowired annotation
@Autowired default injection assembly in accordance with the type, default it requires dependent objects must exist (be it the required property is set false). @Autowired annotation provides a more fine-grained control, including where and how to complete the automatic assembly. And its use as @Required modified setter method, constructor, or a PN method of any attribute names and / or a plurality of parameters.

And the difference between the @Autowired @Resource
@Autowired may be used: constructor, member variables, methods Setter

The difference between @Autowired and @Resource

@Autowired default injection assembly in accordance with the type, default it requires dependent objects must exist (be it the required property is set false).

@Resource default is to assemble injected by name, only if can not find a name that matches the type of bean will be assembled in accordance with the injection.

What is the role @Qualifier annotation
When you create more of the same type of bean and want to use only attribute in which the assembly of a bean, you can use annotations and @Qualifier @Autowired to disambiguate by specifying exactly which bean should be assembled.

which classes exist API in spring JDBC?
JdbcTemplate

SimpleJdbcTemplate

NamedParameterJdbcTemplate

SimpleJdbcInsert

SimpleJdbcCall

What JdbcTemplate
JdbcTemplate class provides many convenient solutions to transform such data into the database basic data types or objects, database operations execute written statement or callable, providing custom data error handling.

CGLIB difference JDK dynamic proxies and dynamic proxy
Spring dynamic proxy AOP mainly in two ways, JDK dynamic proxies and CGLIB dynamic proxies:

JDK dynamic proxies only provide agent interface does not support proxy class. InvocationHandler core interfaces and Proxy classes, called through InvocationHandler invoke () method reflection code in the target class, dynamically cross woven together and business logic; Next, using Proxy InvocationHandler dynamically create an instance of an interface of compliance, generate a proxy object target class.

If the agent had not realized InvocationHandler interfaces, then Spring AOP will choose to use dynamic proxy CGLIB target class. CGLIB (Code Generation Library), code generation is a class library, a dynamically generated object is a subclass of the specified class at runtime, and wherein the cover and the specific method of adding a reinforcing code to achieve AOP. CGLIB by inheritance way to do dynamic proxy, so if a class is marked as final, it can not be used for dynamic CGLIB agent.

Static and dynamic proxy agent difference is the generation timing AOP proxy object, relatively static AspectJ proxy mode with better performance, but requires a specific compiler AspectJ processing, and do not need specific Spring AOP compiler process.

Explain a few terms Spring AOP inside
(1) section (Aspect): section is a combination of notification and the point of tangency. Notification and cut-off point together define the entire contents of the section. In Spring AOP, aspects are implemented using class (style based mode) or @AspectJ annotation to be implemented in the general category.

(2) a connection point (Join point): refers to a method, in Spring AOP, a connection point always represents a method execution. There are thousands of applications may notice the timing of application. These are called the timing of the connection point. Is the point of attachment can be inserted in the course of the execution of a cut point. This point may be when a method call, an exception is thrown, and even modify a field. Section code can use these points into the normal flow of applications in and add new behavior.

(3) a notification (Advice): in terms AOP, the operating section is referred to as a notification.

(4) pointcut (Pointcut): definition of the tangent point would match one or more connection points to be woven into the notification. We usually use explicit class and method names, class and method names or use regular expressions to match the definition to specify these cut points.

(5) into (Introduction): the introduction of a new method allows us to add to an existing class or attribute.

(6) target object (Target Object): being notified by one or more section (aspect) (advise) object. It is usually a proxy object. Some people call it being notified (adviced) objects. Since Spring AOP is achieved by running a proxy, this object is always to be a proxy (proxied) objects.

(7) weaving (Weaving): weaving section is applied to the target object and create a new proxy object of the process. There are in the life cycle of the target object how many points can be woven into:

Compile: section is woven into the target class compile time. The weaving AspectJ compiler in this way woven into facets.
Loading of class: class loader in the target section is woven when the JVM. Require special class loader, which can be enhanced in the target class of the target class bytecode introduced before application. Weaving to support this way of weaving section when AspectJ5 load.
Runtime: section is woven into applications running at some point. Under normal circumstances, when the weaving section, AOP container will target objects dynamically create a proxy object. SpringAOP in this manner is woven into the section.

发布了438 篇原创文章 · 获赞 2 · 访问量 1万+

Guess you like

Origin blog.csdn.net/qq_37769323/article/details/104623638