Spring Core
I. Introduction:
1. Dependency Injection (DI)
Pros: Decoupling
Spring uses the application context (application context) to load the bean definitions and assemble them.
The Spring application context is responsible for object creation and assembly.
Classpathxmlapplicationcontext Loading Spring Context (classpathxmlapplicationcontext context = new Classpathxmlapplicationcontext ("Meta-inf/spring/xxx.xml"), which can be obtained through the context of the bean)
2. Apply Facets
Aspect-oriented programming (aspect-oriented PROGRAMMING,AOP): You can decouple functionality throughout your application to form reusable components. Separation of concerns.
3.Bean
In spring-based applications, the application object lives in the spring container. The spring container is responsible for creating objects, assembling objects, configuring them, and managing their entire lifecycle, from new to finalize ().
Beans can be named by @component ("Beanname") or @named ("Beanname"). Where @named is provided in the Java Dependency Injection specification.
Spring container is not only one, spring comes with a number of container implementations, can be classified into two different types:
--bean Factory: The simplest container to provide basic DI support;
--Application Context: Build based on beanfactory and provide service at the application framework level. (More applications)
The difference between Beanfactory and Factorybean (https://www.cnblogs.com/redcool/p/6413461.html):
Beanfactory is a factory class that is used to manage a bean's factory. Beanfactory is the core interface of the IOC container, which is responsible for instantiating, locating, configuring objects in the application, and establishing dependencies between these objects.
Factorybean is a bean that implements the Factorybean<t> interface. Based on the bean ID obtained from beanfactory is actually the object returned by Factorybean GetObject () instead of Factorybean itself, to get Factorybean itself requires a & symbol in front of the ID.
Two. Assembling Beans
Assemble the beans that are scanned by the component and their dependencies
1. Automatic scanning of components
@Controller Controller: Inject service
@Service services: Injecting DAO
@Repository DAO: Implementing DAO Access
@Component: Instantiate the normal pojo into the spring container, equivalent to the <bean id= "" class= ""/> in the configuration file
@Controller, @Service, @Repository, @Component annotated classes, and incorporate these classes into the spring container for management.
Introduction of Component Scanning components:
Where Base-package is the package that needs to be scanned (with all child packages)
<context:component-scan base-package= "Com.best"/>
You can use @configuration instead of an XML configuration, @ComponentScan (basepackages={"" "}") to specify the package that scans the component and the class with @component annotations under the sub-package. @ComponentScan the package and child packages for the class that the default scan is in.
@Controller: For labeling control-level components
@Service: For labeling business layer components
@Repository: Used to label data access layer components, DAO components
@Component: A generic component that can be annotated with a component when it is poorly categorized.
@Controller, @Service, @Repository, @Component annotated classes, and incorporate these classes into the spring container for management.
2. Automatic assembly
@Autowired can be used to construct methods and methods of classes. Spring satisfies the dependency declared on the method parameter.
--if there is no matching bean: Spring throws an exception when the application context is created, @autowired (required=false) can be used to avoid exceptions
-when there is a matching bean: if @autowired (Required=false) is used, the non-assembled property may throw nullpointexception when the code does not have a null check.
@Inject can also complete automatic assembly, which is provided in the Java Dependency Injection specification.
Three. Advanced Assembly
@Profile ("dev") -----bean that is assembled for dev environment profile
Use profile to first organize all the different bean definitions into a live multiple profile, to ensure that the corresponding profile processing activation (active) state occurs when the application is deployed to each environment, and only when the specified profile is activated. The corresponding bean will not be created.
Use the @profile annotation to specify which profile a bean belongs to.
To activate the profile method:
--As the initialization parameter of Dispatcherservlet;
--As the context parameter of the Web application;
--As a jndi entry;
--as an environmental variable;
--As a system attribute of the JVM;
--On the integration test class, use the @activeprofiles annotation settings: @ActiveProfiles ("Dev")
@Conditional (Xxxcondition.class) -----to conditionally create beans
You can use a method with @bean annotations, and if a given condition evaluates to true, the bean will be created, or the bean would be ignored.
The class that is set to conditional can be any type that implements the condition interface, which simply provides the implementation of the matches () method. The matches () method returns True to create a bean with @Conditional annotations.
@Autowired
Using automatic assembly allows spring to be fully responsible for injecting bean references into construction parameters and properties, reducing the number of display configurations required to assemble application components.
Spring throws nouniquebeandefinitionexception if more than one bean can match the result.
You can set one of the optional beans as preferred (@Primary, Primary with @component or @bean) or use qualifiers (@Qualifier ("Xxxbeanname"). Qualifier with @autowired) to help spring reduce the range of optional beans to only one bean.
Qualifier can also be used with @component or @bean, setting a beanname for a bean to create a custom qualifier to prevent the Bean class name modification from causing the qualifier specified beanname to be found.
Scope of 1.bean
By default, all beans in the Spring app context are created as a single instance (singleton). That is, no matter how many times a given bean is injected into another bean, the same instance is injected each time.
When the classes used are heterogeneous (mutable), they maintain some state, and reuse is not secure at this time.
Spring defines a variety of scopes that can be used to create beans based on these scopes:
--Singleton (Singleton): In the entire application, only one instance of the bean is created;
--Prototype (Prototype): A bean instance is created each time it is injected or acquired through the spring application context;
--session: In a web app, create a bean instance for each session;
--Request: In the Web App, create a bean instance for each request.
The singleton is the default scope, and if you want to select a different scope, use @scope annotations with the @component or @bean:
--Prototypes: @Scope (Configurablebeanfactory.scope_prototype) or @scope ("PROTOTYPE")
--session: @Scope (Value=webapplicationcontext.scope_session, proxymode=scopedproxymode.interfaces)
--Request: @Scope (Value=webapplicationcontext.scope_request, proxymode=scopedproxymode.interfaces)
When a session or request-scoped bean (beansession) is to be injected into a singleton-scoped bean (beansingle), some problems occur:
--Beansingle is created when the spring application context loads, and spring attempts to inject beansession into Beansingle, at which point the beansession does not exist (it will not be created until a user enters the system and the session is created).
-There may be multiple beansession in the system, and in most cases we don't want to inject a fixed beansession into Beansingle, but the one in the current session.
To solve this problem, spring does not inject the actual beansession into the beansingle, but instead injects a beansession agent. This agent exposes the same method as Beansession, and Beansingle will consider it an ordinary beansession.
@Scope annotations have a Proxymode property that is used to configure the proxy. There are two ways of doing this:
--Scopeproxymode.interfaces, which indicates that the agent implements the Beansession interface and delegates the invocation to the specific implementation bean. This method requires Beansession to be an interface.
--Scopeproxymode.target_class, which indicates that spring uses Cglib to generate an extension of the target class to create the proxy. This approach applies to beansession that are specific to the class.
2. Run-time-value injection
Dependency injection usually refers to injecting one bean reference into another bean's property or constructor parameter. It usually refers to associating an object with another object.
Dependency injection is the ability to decouple components and other components of their collaboration.
Another aspect of the bean's assembly is the injection of a value into the bean's property or constructor parameters.
Two ways to evaluate the runtime of spring:
--Attribute placeholder (property placeholder): more simple;
--Spring Expression language (spel): Strong.
Placeholder in the form of "${...}" Wrapper property name, using XML to configure the spring context namespace:
<context:property-placeholder location= "Classpath*:redis.properties,classpath*:shiro.properties" Ignore-unresolvable= "true"/><!--remember Cookie--><bean id= "Remembermecookie" class= " Org.apache.shiro.web.servlet.SimpleCookie "><constructor-arg value=" ${shiro.cookie.name.prefix}-rememberme "/><property name=" HttpOnly "value=" true "/><property name=" MaxAge "value=" 2592000 "/></bean>
The spring expression language is able to assemble values into bean properties and constructor parameters in a powerful and concise way, and the expressions used in this process are evaluated at run time.
Spel has the following features:
--Use the Bean's ID to refer to the bean;
--Invoking the method and accessing the object's properties;
--Arithmetic, relational and logical operations on values;
--Regular expression matching;
--set operation.
Spel expression to be put to "#{...}" Among
<bean id= "Remembermemanager" class= "Org.apache.shiro.web.mgt.CookieRememberMeManager" ><!–rememberme A cookie-encrypted key suggests that each item is not the same as the default AES algorithm key length (128 256 512 bit) –><property name= "Cipherkey" value= "#{t ( ORG.APACHE.SHIRO.CODEC.BASE64). Decode (' ghxh6g3lfh8zb3nworgffa== ')} "/><property name=" cookie "ref=" Remembermecookie "/></bean>
Spring Real-Day notes: Spring core (i)