Today is the 11th day of my study in Lebyte Education, and the main content of my study today is Spring IOC
Spring is one of many open source Java projects. It is a one-stop lightweight open source framework for layered Java EE applications. The main core technologies are IOC (Inversion of control/dependency injection) and AOP (aspect oriented), which realize easy decoupling of projects in the development process and improve the development efficiency of projects. Introducing Spring into your project immediately brings the following benefits: reducing coupling between components and decoupling between layers of software. You can use many of the services provided by the container, such as transaction management services, messaging services, and so on. When we use container-managed transactions, developers no longer need to manually control transactions. There is no need to deal with complex transaction propagation. The container provides singleton support, eliminating the need for developers to write their own implementation code. The container provides AOP technology that makes it easy to implement functions such as permission interception and runtime monitoring. Spring has about 20 modules in total, made up of more than 1300 different files. These components are integrated in Core Container, Aop (Aspect Oriented Programming), and Device support, and Data access and integration, respectively Access/Integeration), Web, message sending (Messaging), test 6 modules set.
Core container: Spring-beans and spring-core modules are the core modules of the Spring framework, Containing Inversion of Control (IoC) and Dependency Injection (DI), the core container provides the basic functionality of the Spring framework. The main component of the core container is the BeanFactory, the implementation of the factory pattern. BeanFactory uses inversion of control (IOC) ideas to separate application configuration and dependency specifications from the actual application code. Spring Context: The Spring Context is a configuration file that provides Context information to the Spring framework. The Spring context includes enterprise services, such as JNDI, EJB, E-mail, internationalization, validation, and scheduling capabilities. Spring-expression module is an extension module of Unified EL. It can query and manage running objects, call object methods, operate arrays, and collections conveniently. Its syntax is similar to traditional EL, but it provides additional functionality, most notably function calls and simple string template functions.
Spring-aop: Spring-AOP is another core module of Spring. In Spring, it is based on the DYNAMIC proxy technology of the JVM, and then designs a series of CROSScutting implementations of AOP, such as pre-notification, return notification, exception notification, etc. With its configuration management features, the Spring AOP module integrates section-oriented programming capabilities directly into the Spring framework. So, you can easily make any object managed by the Spring framework AOP enabled.
Spring Data Access: Spring-jdbc module consists of spring-JDBC, Spring-TX, spring-ORM, spring-JMS and spring-OXM. Spring-jdbc module is the main implementation module of JDBC abstract framework provided by Spring. For simplifying Spring JDBC. The Spring-TX module is the SpringJDBC transaction control implementation module. Using the Spring framework, transactions are well encapsulated and can be configured flexibly at any layer through its Aop configuration. Spring-orm module is an Orm framework support module, mainly integrating Hibernate, Java Persistence API (JPA) and Java Data Objects (JDO) for resource management, Data access object (DAO) implementation and transaction strategy. The Spring-JMS module (Java Messaging Service) can send and receive messages. The Spring-OXM module mainly provides an abstraction layer to support Oxm (Oxm stands for object-to-XML-Mapping, which is an O/M-mapper that maps Java objects to XML data or XML data to Java objects), for example: JAXB, Castor, XMLBeans, JiBX, XStream, and more.
The Web module: It is composed of spring-Web, Spring-WebMVC, Spring-WebSocket and spring-WebMVC-portlet. The Web context module is built on the application context module and provides the context for web-based applications. The Web module also simplifies handling multi-part requests and binding request parameters to domain objects.
Message sending: namely, the Spring-Messaging module. Spring-messaging is a new module added in Spring4. Its main responsibility is to integrate some basic message delivery applications for the Spring framework.
Unit tests: that is, the Spring-test module. The Spring-test module mainly provides support for testing
JDK version: JDK 1.7 or later Spring version: Set the project’s coordinates. Set the project’s Maven environment. Set the project’s name and the workspace to store
Modify the JDK version < project. Build. SourceEncoding > utf-8 < / project. Build. SourceEncoding > Piler < maven.com. Source > 1.8 < / maven.com piler. Source > < maven.com piler. Target > 1.8 < / maven.com piler. Target >
Modified unit test JUnit version JUnit JUnit 4.12 test
The pluginManagement tag in the Build tag
Add the Spring framework dependency coordinate Maven repository: mvnrepository.com/
Org.springframework Spring-context 5.2.4.RELEASE Write the Bean object package com.xxxx.service; public class UserService { public void test(){ System.out.println(“Hello Spring!” ); }} Add the Spring configuration file to the project SRC folder resources (Alt+insert)
Mark Resources as a resource directory
Create a new spring. XML file under SRC \main\ Resources and copy the template content provided by the official documentation into the XML. Configure beans into XML and incorporate the corresponding beans into the Spring container to manage Spring.xml
Configure the Bean object in spring.xml
Load the configuration file and get the instantiation object package com.xxxx; import com.xxxx.service.UserService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; Public class App {public static void main(String[] args) {// Get Spring context (load configuration file) ApplicationContext AC = new ClassPathXmlApplicationContext (” spring. XML “); // Get the Bean object instantiated in the Spring container by using the getBean method (UserService) ac) getBean (” UserService “); // Call the method (using the instantiation object) userservice.test (); }}Spring IOC container Bean object instantiation
Defines a Bean factory interface that provides methods to get beans
Define the Bean factory interface implementation class, parse the configuration file, and instantiate the Bean object
Implement the get Bean method
Define the Bean property object package com.xxxx.spring; /** * public class MyBean {private String id; // Bean object id attribute value private String clazz; Public MyBean() {} public MyBean(String id, String clazz) {this.id = id; this.clazz = clazz; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getClazz() { return clazz; } public void setClazz(String clazz) { this.clazz = clazz; }} Add dom4j coordinate dependencies dom4j dom4j 1.6.1 JAXEN jaxen 1.1.6 Prepare the custom configuration file spring.xml
Create the Bean object userservice.java package com.xxxx.service that corresponds to the configuration file. Public class UserService {public void test(){system.out.println (” UserService test… ); }} AccountService.java package com.xxxx.service; Public class AccountService {public void test(){system.out.println (” AccountService test… ); }}
Test whether the instantiated Bean object package com.xxxx can be retrieved; import com.xxxx.spring.MyFactory; import com.xxxx.spring.MyClassPathXmlApplicationContext; import com.xxxx.service.AccountService; import com.xxxx.service.UserService; public class App { public static void main(String[] args) { MyFactory factory = new MyClassPathXmlApplicationContext (” spring. XML “); // Get the instantiated object UserService UserService = (UserService) factory.getBean(” UserService “); userService.test(); UserService userService2 = (UserService) factory.getBean(” UserService “); System.out.println(userService+”=====” + userService2); AccountService AccountService = (AccountService) factory) getBean (” AccountService “); accountService.test(); }} The Spring container reads the XML configuration information at startup, instantiates the configured bean, and retrieves the configured bean object via the context object’s getBean() method. This enables the external container to automatically maintain and create beans.
The Spring IOC configuration file loads spring.xml
The Spring framework can load multiple configuration files into the environment when it starts. For complex projects, there may be multiple profiles that are loaded simultaneously when the project starts deployment. service.xml
dao.xml
spring.xml
Only when the loading load total configuration file / / load the total resource file ApplicationContext ac = new ClassPathXmlApplicationContext (” spring. XML “); Spring IOC container Bean object instantiation constructor Instantiation Note: Empty constructor created by default constructor must exist otherwise creation fails
Set up the configuration file spring.xml
Access to instantiate objects ApplicationContext ac = new ClassPathXmlApplicationContext (” spring. XML “); UserService UserService = (UserService) ac.getBean(” UserService “); userService.test();
Static factory instantiation note: To have the factory class and factory methods factory methods are static
Define the static factory class package com.xxxx.factory; import com.xxxx.service.UserService; Public class StaticFactory {/** define the corresponding static method, Public static UserService createUserService() {return new UserService(); }}
Set up the configuration file spring.xml
Access to instantiate objects ApplicationContext ac = new ClassPathXmlApplicationContext (” spring. XML “); UserService UserService = (UserService) ac.getBean(” UserService “); userService.test(); When we specify that Spring uses static factory methods to create Bean instances, Spring first parses the configuration file and, based on the information specified in the configuration file, invokes the static factory method of the static factory class through reflection, taking the return value of the static factory method as the Bean instance. In this process, Spring is no longer responsible for creating Bean instances, which are provided by static factory methods provided by the user.
Note: Factory methods for non-static methods require the factory bean to be configured and the factory-bean, factory-method properties to be configured in the business bean
Define the factory class package com.xxxx.factory; import com.xxxx.service.UserService; Public class InstanceFactory {public class InstanceFactory { * @return */ public UserService createUserService() {return new UserService(); }}
Set up the configuration file spring.xml
Access to instantiate objects ApplicationContext ac = new ClassPathXmlApplicationContext (” spring. XML “); UserService UserService = (UserService) ac.getBean(” UserService “); userService.test();
Compare the three ways Spring instantiates beans
Method 1: Create from the bean’s default constructor, which can be used when the business logic of each bean is relatively independent of each other or less associated with the outside world.
Method 2: using static factory method to create, you can unified management of the creation of each bean, such as each bean before the creation of the same initialization process, you can use the factory method for unified processing and so on.
Method 3: instantiate factory method creation, that is, factory method also as a business bean to control, 1 can be used to integrate other framework bean creation management method, 2 can make bean and factory role swap. In development projects, there is usually one way to instantiate beans. Project development basically adopts the first way, which is hosted by Spring and used directly. Two other understandings
Spring IOC injection manual instantiation vs. external introduction Figure 1: Figure 2: Comparison found: In Figure 2, the creation of the UserDao object is not actively de-instantiated as shown in Figure 1. Instead, the UserDao is passed in as a parameterized method to realize the dependence of UserService on the UserDao class. The actual objects behind the scenes are created externally. Spring supports four types of injection: Set injection, constructor injection, static factory injection, and instance factory injection. Note: Property fields need to provide four set methods. You are advised to use the set method to inject service object Javabeans
The property field provides the set method