This is the 25th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
❤️ About the author: Hello everyone, I am Xiao Xu Zhu. Java field quality creator 🏆, CSDN blog expert certification 🏆, Huawei Cloud enjoy expert certification 🏆
❤️ technology live, the appreciation
❤️ like 👍 collect ⭐ look again, form a habit
Review:
Spring Framework – Understanding the Spring Framework (part 1)
Some of the concepts mentioned in the previous chapter will be explained in detail in this chapter
What is the IOC
IoC(Inversion of Control) includes two aspects: first, Control. Second, the inversion
Classes and class dependencies are left to the container. IoC is not a technology, just an idea, an important object-oriented programming discipline that can guide us in designing loose-coupled, better programs.
IOC is not straightforward enough, so Martin Fowler proposed DI(Dependency injection) to replace IOC, that is, the calling class’s dependency on an interface implementation class is injected by a third party (container or collaboration class) to remove the calling class’s dependency on an interface implementation class.
There are two ways to IOC: DI(dependency injection) and DL (dependency lookup)
The advantages of the IOC
- Reduces object creation and management, making code hierarchies clearer.
- Spring’s IOC container is a lightweight container that is non-invasive (doesn’t rely on the container’s API) and doesn’t require special interfaces to be implemented.
- Encourage us to program toward interfaces.
- It reduces the coupling of the code, pushing the coupling parts into the configuration file, and only changing the configuration file if their relationship changes.
DL (dependent lookup)
The program provides the lookup method, and the container provides the callback interface and context to the component. EJB and Apache Avalon both use this approach
The following code shows the dependency lookup mechanism based on the JNDI implementation.
public class MyBusniessObject{ private DataSource ds; private MyCollaborator myCollaborator; public MyBusnissObject(){ Context ctx = null; try{ ctx = new InitialContext(); Ds = (DataSource) CTX. Lookup (" Java: comp/env/dataSourceName "); MyCollaborator = (myCollaborator) CTX. Lookup (" Java: comp/env/myCollaboratorName "); }...Copy the code
However, EJB equivalents are rarely used in daily development, so it’s not surprising that many of you haven’t heard of DL (dependency lookup), and are more familiar with DI (dependency injection).
But these two lookups you should have used before:
- Name lookup – autowireByName
- Type lookup – autowireByType
Name lookup – autowireByName
You can simply pull the bean directly from the BeanFactory, which is usually @qualifier
Type lookup – autowireByType
A common one is @autowire
If a bean of the same type as the specified property exists in the container, it is automatically assembled with that property. If there are more than one bean of this type, an exception will be thrown
The simple idea is to match by class name
DI(Dependency injection)
Instead of creating callers in code when one object needs another, it relies on external containers that create and pass them to the program
To illustrate, traditional programming, as shown in Figure 1, takes the initiative to create related objects and then combine them:
Figure 1
When you have an IoC/DI container, these objects are no longer actively created in the client class, as shown in Figure 2
Figure 2
The IOC container
The IOC container is essentially a big factory that manages all of our objects and dependencies.
- The principle is through Java reflection technology to achieve! By reflection we can get all the information about a class (member variables, class names, etc.)!
- The relationships between classes are described through configuration files (XML) or annotations
- We can use this configuration information and reflection techniques to build corresponding objects and dependencies!
Spring container (Bean Factory)
- BeanFactory: This is basic, Spring-oriented
- ApplicationContext: This is on top of BeanFactory for developers using the Spring framework. Offers a range of features!
ApplicationContext is familiar to most spring applications
BeanFactory is different from ApplicationContext
A BeanFactory can be thought of as a factory class that contains a collection of beans. The BeanFactory contains the definition of a bean to instantiate when a client request is received.
BeanFactory can also generate relationships between collaborating classes when instantiating objects. This frees up the configuration of the bean itself and the bean client. BeanFactory also includes control of the bean lifecycle, calling client-side initialization methods and destruction methods.
Applicationcontext is a subinterface to the beanFactory and has all the functionality of the beanFactory, but it also provides additional functionality on top of it.
- Text messages that support internationalization are provided
- Unified resource file reading method
- Events for beans that have been registered in listeners
- And the beanFactory is lazy-loaded, creating instances of classes when they are needed, whereas the ApplicationContext loads all singleton beans at initialization
Here are three more common implementations of ApplicationContext:
1, the ClassPathXmlApplicationContext: read the context from the classpath XML configuration files, and generate the context definition. The application context is obtained from the program environment variable
ApplicationContext context = new ClassPathXmlApplicationContext (" bean. XML ");Copy the code
2, FileSystemXmlApplicationContext: from the XML configuration file read the context in the file system.
ApplicationContext context = new FileSystemXmlApplicationContext (" bean. XML ");
XmlWebApplicationContext: The XML file of the Web application reads the context.
The life cycle of Spring beans
The life cycle of Spring beans is straightforward. When a bean instance is initialized, a series of initialization operations need to be performed to reach a usable state. Similarly, when a bean is not being called, it needs to be destructed and removed from the bean container.
The Spring Bean Factory is responsible for managing the life cycle of beans that are created in the Spring container. The Bean life cycle consists of two sets of call back methods.
- The callback method invoked after initialization.
- Destroys the previously called callback method.
The Spring framework provides four ways to manage bean lifecycle events:
-
InitializingBean and DisposableBean callback interfaces
-
Other Aware interfaces for specific behaviors
-
The Custom init() and destroy() methods are in the Bean configuration file
-
@postConstruct and @PreDestroy annotation methods
Examples of code to manage the bean life cycle using the customInit() and customDestroy() methods are as follows:
<beans> <bean id="demoBean" class="com.somnus.task.DemoBean" init-method="customInit" destroy-method="customDestroy"> </bean> </beans> Copy the code
Assemble Bean mode
There are four ways for Spring4.x to start the IOC container assembly of beans:
- The XML configuration
- annotations
- JavaConfig
- Groovy DSL configuration (which is rare)
In daily development, XML configuration + annotations are commonly used.
The remaining two are interested in baidu + Google
Dependency injection
Dependency injection can be done in three ways:
- Properties into— >
setter()
Methods to inject - Constructor injection
- Factory method injection
What is the difference between constructor injection and property injection
- Most dependency injection is supported in the property injection method. If we only need to inject int, string, and long variables, we should not use set method injection. For primitive types, we can set default values for primitive types if we have no injection. Most dependency injection is not supported in constructor injection because the constructor must be called with the correct construction parameters, otherwise an error is reported.
- Property injection does not override the constructor’s value. If we use both constructor injection and set injection on the same variable, the constructor will not override the value injected by the set method. This is obvious because the constructor is called when the object is created.
- There may be no guarantee that a dependency has been injected when using property injection, which means that the object’s dependencies may be incomplete. Constructor injection, on the other hand, does not allow the generation of objects with incomplete dependencies.
- If object A and object B depend on each other during property injection, Spring throws S when object A is created
ObjectCurrentlyInCreationException is unusual, because A before B object is created object cannot be created, and vice versa. So Spring solves the problem of loop dependency with set injection, because object set methods are called before the object is created.
The scope of the Bean
Beans in the Spring container fall into five categories. All scope names are self-explanatory, but to avoid confusion, let’s explain:
If you use the 3, 4, and 5 scopes, you need to manually set the proxy
- 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.
- Prototype: Multiinstance scope as opposed to singleton scope, provides one instance for each bean request.
- Request: An instance is created in the scope of the request bean for each network request from the client. After the request completes, the bean is invalidated and collected by the garbage collector.
- Session: Similar to request scope, ensure that there is an instance of a bean in each Session and that the bean is invalidated after the Session expires.
- Global-session: global-session is related to Portlet applications. When your application is deployed to work in a Portlet container, it contains many portlets. If you want to declare that all portlets share global stored variables, the global variables need to be stored in global-session. The global scope has the same effect as session scope in the Servlet.
Automatic assembly of beans
The autowire attribute of the bean element is used to specify the autowire of the bean definition. There are five patterns:
- No By default, the bean is assembled manually by setting the ref property without autowiring
- The byName dependent bean name needs to match the name referenced in the class to match the dependency. The name we referenced in the class is userAutowireDao, so we will match our userAutowireDao method
- ByType is automatically assembled by the data type of the parameter. If the data type of one bean is compatible with the data type of another bean’s property property, it is automatically assembled by the class name
- Parameters in the construct constructor are automatically assembled in the form of ByTypes.
- Default is determined by the default-Autowire attribute of the parent tag
.
Commonly used notes explained in detail
Annotation injection replaces the registration and dependencies of beans in our XML configuration file with annotation tags
@Component
Used in the class
All classes can be written this way, general annotation, this is not standard writing, hahaha
@Repository
Used in the class
This annotation mainly declares the dao’s class component
@Service
This annotation basically declares the Service service class
@Controller
Mainly declarative control classes (SpringMVC/Struts2 Action/Controller)
@Resource
Used inside a class
JavaEE annotations are injected by byName by default. If byName cannot be found, byType will be used to match
The effect is the same as Autowired, with the lookup order reversed
The @Resource attribute has two important attributes: name and type. Spring interprets the @Resource attribute name to the bean name, and the type attribute to the bean 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 automatic injection policy is used through reflection.
@Autowired
Used inside a class
Spring annotations, by default, are injected as byType – if there are more than one implementation class, it matches byName (@qualifier)
The result is the same as Resource, the search order is reversed
Autowired is used with Qualifier,
eg:
@Autowired
@Qualifier(value = “TestService2”)
private TestService testService;
/ / implementation class
@Service(“TestService1”)
public class TestServiceImpl implements TestService {… }
/ / implementation class
@Service(“TestService2”)
public class TestServiceImpl implements TestService {… }
@Qualifier
Spring annotations that specify the method name to implement
@Scope
The scope of the bean, which you can see above, will not be repeated here
conclusion
Drawing on the ideas of other bloggers: I will sort out the Spring mind map and put it out when AOP is written.
That’s all for today’s spring introduction, goodbye!
References:
- Proficient in Spring4.x Enterprise Application Development
My.oschina.net/u/3777556/b… Spring IOC knowledge all in one!
www.zhihu.com/question/48… What do you think of Spring
www.cnblogs.com/liangyihui/… Most complete Spring interview questions and answers
Blog.csdn.net/sunqingzhon… Spring Notes – 5 modes for bean auto-assembly (Autowrite attribute)