1. What is Spring
Spring is an open source framework dedicated to simplifying enterprise application development, mainly through lightweight and minimal intrusive programming based on Pojo, loose coupling through dependency injection and interface-oriented programming, application logic and system services separation based on cut-through programming, and a reusable component that reduces boilerplate code through slices and templates.
2. The life cycle of the bean in spring, the instance obtained from Beanfactory or ApplicationContext is singleton, which means that the alias for each bean can only maintain one instance. Instead of generating a new object each time using the singleton pattern to produce a single instance, there is no problem with single-threaded programs, but for multithreaded programs, you must pay attention to security (THREAD-SAFE) issues, Prevents data synchronization problems caused by multiple threads accessing shared resources at the same time.
In spring, however, you can set a new instance each time you specify an alias from Beanfactory or ApplicationContext and get a bean
In spring, the Singleton property defaults to True, and only if it is set to false, a new instance is generated each time the bean obtained by the alias is specified
A bean from creation to destruction, if it is built with Beanfactory, manages the bean, and goes through several stages of execution (Figure 1.1):
The establishment of 1:bean:
The container looks for and instantiates the bean's definition information.
2: Attribute injection:
Using dependency injection, spring configures all of the bean's properties according to the Bean definition information
3:beannameaware's Setbeanname ():
If the Bean class has an implementation Org.springframework.beans.BeanNameAware interface, the factory calls the Bean's Setbeanname () method to pass the Bean's ID.
4:beanfactoryaware's Setbeanfactory ():
If the Bean class has an implementation Org.springframework.beans.factory.BeanFactoryAware interface, the factory calls the Setbeanfactory () method to pass in the factory itself.
5:beanpostprocessors's Processbeforeinitialization ()
If there is a org.springframework.beans.factory.config.BeanPostProcessors and Bean Association, then its postprocessbeforeinitialization () Method will be called
6:initializingbean's Afterpropertiesset ():
If the Bean class has implemented the Org.springframework.beans.factory.InitializingBean interface, execute his afterpropertiesset () method
Init-method defined in 7:bean definition file:
You can use the "Init-method" property in the bean definition file to set the method name, for example: If you have the above settings, the execution of the Initbean () method is performed at this stage
8:beanpostprocessors's Processaafterinitialization ()
If any of the Beanpostprocessors instances are associated with the bean instance, the Processaafterinitialization () method of the Beanpostprocessors instance is executed. At this point, the bean can already be used by the application system and will remain in the beanfactory knowing it is not in use. There are two ways to remove it from the Beanfactory
1:disposablebean's Destroy ()
When the container is closed, if the Bean class has an implementation Org.springframework.beans.factory.DisposableBean interface, execute his destroy () method
Destroy-method defined in 2:bean definition file
You can use the "Destroy-method" property to set the method name in the bean definition file when the container is closed
If this is the case, the Destroy () method is executed at this stage, and if the bean is generated and managed using ApplicationContext, it is slightly different. Using ApplicationContext to generate and manage bean instances, after performing the setbeanfactory () phase of Beanfactoryaware, If a Org.springframework.context.ApplicationContextAware interface is implemented on the Bean class, its setapplicationcontext () method is executed. The Processbeforeinitialization () and subsequent processes of the beanpostprocessors are then executed.
3. The ApplicationContext and beanfactory distinctions in spring are beanfacotry the more primitive factory in spring. such as Xmlbeanfactory is a typical beanfactory. The original beanfactory cannot support many of spring's plug-ins, such as AOP features, Web applications, and so on.
ApplicationContext interface, which is derived from the Beanfactory interface, and thus provides all the functionality of the beanfactory. ApplicationContext works in a more framework-oriented way and hierarchies and implements inheritance for contexts, the ApplicationContext package also provides the following features:
Messagesource, providing internationalized message access
• Resource access, such as URLs and files
• Event Propagation
• Load Multiple (inherited relationships) contexts so that each context is focused on a particular level, such as the application Web layer
1). Beanfactroy takes the form of deferred loading to inject the bean, that is, only when a bean is used (called Getbean ()), the bean is loaded instantiated, so that we cannot discover some of the existing spring configuration problems. ApplicationContext, in contrast, creates all the beans at a time when the container is started. In this way, when the container starts, we can discover the configuration errors that exist in spring.
2). Beanfactory and ApplicationContext all support the use of beanpostprocessor, beanfactorypostprocessor, but the difference between the two is: Beanfactory need to manually register, And ApplicationContext is automatically registered
4. The benefits of Spring's JDBC and DAO modules using JDBC programming typically results in a large number of boilerplate code, such as getting a database connection, creating statements, processing a result set, and finally shutting down a database connection. Spring's JDBC and DAO modules Abstract These boilerplate code, making our database code concise and avoiding problems caused by the failure to shut down database resources. The module constructs a semantic-rich exception layer on top of a variety of database service error messages, and we don't need to explain the obscure proprietary SQL error messages later.
5. Spring assembly mechanism 1 display configuration in XML
2 Display configuration in Java
3 The Hermit's bean discovery Mechanism and automatic assembly mechanism
6. Automated assembly Plan One:
1 component Scan: Spring automatically discovers the bean created in the application context. For example, a bean using a @component annotation annotation.
<context:component-scan base-pacage= "" >
2 Automatic assembly: Spring automatically satisfies the dependencies between the beans. Use the @autowired annotation Scheme II:
1 Add the annotation @configuration on the class to indicate that this class is a configuration class
2 Add the annotation @componentscan on the class, which indicates the automatic scan configuration, and automatically scans the classes in the package in which the class resides by default. You can set up a scan package
Componentscan (basepackage={"One", "two"}) or set
Componentscan (Basepackageclasses{a.class,b.class})
7. Assemble the bean 1 through Java code to add a @bean annotation to the method, which takes the ID of the method named Bean
2 The annotation will automatically assemble the Bean 8 in the parameter. Assemble bean 1 through XML basic format
<bean id = " class=" >
2 constructor initialization
<bean id = "class =" ">
<constructor-arg ref=" "/>
<constructor-arg value=" "/>
<!-- Injected null-->
<constructor-arg><null/></constructor-arg>
<!--list collection-->
< constructor-arg>
<list> <value></value> </list> </constructor-arg>
<! --Set Set-->
<constructor-arg>
<set>
<ref bean= "/>
<ref bean=" "/>
</set>
</constructor-arg>
</bean>
3) Attribute Injection
<bean id = "class =" ">
<property name=" "value=" "/> <property name=
" "ref=" "/>
<!-- List collection-->
<property name= "" > <list> <value></value> </list> </property> <!--set Set-->
<property name= ">
<set>
<ref bean=" "/> <ref bean=
" "/>
</set>
</property>
</bean>
9. Import and mixed configuration 1 Add annotations to the class @import import class @import (One.class)
2 Add annotation on class @importresource ("" Classpath:one.xml "")
3 Use <import resource= ""/> in XML
Profile solution load different configuration 1 across the environment
@Configuration
@Profile ("dev") Public
class decelopmentprofileconfig{
@Bean public
DataSource DataSource () {return
new DataSource ();
}
}
2 Configure on the method
@Configuration public
class decelopmentprofileconfig{
@Bean
@Profile ("dev") public
DataSource DataSource () {return new DataSource ();}
@Bean
@Profile ("prod") public
DataSource DataSource () {return new DataSource ();}
}
3) Configuring in XML
<beans prifile= "Dev" >
</beans>
4) Activate profile
When spring determines which profile is active, it needs to rely on two separate properties: Spring.profiles.active and Spring.profile.default
Programme I
Configuring Parameters in Web.xml
<conext-param>
<param-name>spring.profiles.default</param-name>
<param-value> dev</param-value>
</context-param>
<servlet>
<servlet-name>servlet</ Servlet-name>
<servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class >
<init-param>
<param-name>spring.profiles.default</param-name>
< param-value>dev</param-value>
</init-param>
</servlet>
Programme II
Use annotation @activiteprifile ("")
@Conditional annotation Condition Initial bean
@Bean
@Conditional (magicbeancobdition.class) public
Magicbean Magicbean () {return
Magicbean ();
}
public class Magicbeancondition implements Condition{public
Boolean matches (Conditioncontext context) {
Environment env = context.getenvironment ();
Return Env.containsproperty ("Magic");
}
12. Handling automatic assembly ambiguity 1 Preferred settings
annotation @primary or XML configuration primary= "true"
2) Qualifier
Use annotation @qualifier ("")
3) Custom Qualifier
Scope 1 of Bean) single case (Singleton)
2) prototype (Prototype)
3 Sessions (session)
4) Requests (request)
Mode one:
Use annotations @scope (Configurablebeanfactory.scope_prototype)
Mode two:
Configuring Scope= "prototype" in XML
14. Aspect-oriented programming dynamically moves code into the specified method of the class at run time, and the programming idea at the specified location is the aspect-oriented programming.
Provides rich support for aspect-oriented programming in spring, allowing for cohesive development through separation of application business logic and system-level services such as audit (auditing) and transaction (transaction) management. Application objects only implement what they should do--complete the business logic--that's all. They are not responsible (or even conscious) of other system-level concerns, such as logs or transactional support.
AOP Terminology NOTICE: The notification defines what the slice is and when it is invoked. Notifications are mainly divided into: forward notification (before), post notification (after), return notification (after-returning), exception Notification (after-throwing), and surround notification (Around).
Combo point: A point in which slices can be inserted during application execution
Tangency: The notification defines what the slice is and when, and where the pointcut is defined. The definition of the pointcut matches one or more connection points to which the notification is to be woven.
Cut surface: A combination of notifications and pointcuts. Notifications and pointcuts together define the entire content of the slice-what it is and when and where it functions.
Introduction: Allows us to add new methods and properties to existing classes
Weaving: The process of applying a slice to a target object and creating a new proxy object. Weaving is mainly in the compile period, class loading period and running period.
Spring support for Aop 1 The classic spring AOP based on proxy
2) Pure Pojo slice
3 @AspectJ annotation-driven slices
4) Injection Type ASPECTJ slice
17. Use slice 1 to define cut section
@Aspect public
class audience{
@Pointcut ("execution concert. Performance.perform (..)) ")
The public void performance () {}
@Before ("Performance ()") is public
void Takeseates () {}
@AfterReturning (" Execution (* * concert. Performance.perform (..)) ")
public void Applause () {}
}
2 Enable ASPECTJ in Java
@Configuration
@EnableAspectJAuroProxy
@ComponentScan public
class concertconfig{
@Bean
Public audience audience () {return
new audience ();
}
}
3 Configure enable ASPECTJ in XML
<aop:aspectJ-autoproxy>
<bean class= "Audience" >
4 declaring slices in XML
<aop:config>
<aop:aspect ref= "Audience" >
<aop:pointcut id= "Performance" Execution (* * concert. Performance.perform (..)) " />
<aop:before pointcut-ref= "Performance" method= "" >
<aop:after-returning pointcut= " Execution= "* * concert. Performance.performance (..) " Method= "" >
</aop:aspect>
</aop:config>