IOC concept and principle
IOC concept
IOC (Inversion of control)
- The process of creating and calling objects is handed over to Spring for management
- Purpose of using IOC: reduce coupling
IOC entry case: https://blog.csdn.net/CherryChenieth/article/details/123043600?spm=1001.2014.3001.5501
IOC underlying principle: xml parsing + factory schema + reflection
If users want to get a circle, they just need to tell the factory that I want a "Cicle", without understanding the specific details of building a circle. In terms of code, the client only needs to call shape = shapefactory getShape("Circle"); You can get a circle object without explicitly using circle = new circle();.
Using the factory pattern can reduce the coupling between classes.
Inversion of control (IOC) is a principle in design patterns, which is embodied in Java as "reflection". Generally speaking, reflection is to generate objects according to the given class name (string). This programming method allows the application to dynamically decide which object to generate at run time.
Combined with factory mode + reflection, IOC uses a factory class to dynamically obtain the required objects through runtime, and requires the factory class to generate corresponding objects.
Code example
Step 1: configure the created object in the xml configuration file
<bean id="dao" class="com.cherrychen.UserDao"></bean>
Step 2: create a factory class after the existing service class and dao class
class UserFactory{ public static UserDao getDao(){ String classValue = class Attribute value; //1. Here is the class string "com.cherrychen.UserDao" obtained through xml parsing Class clazz = Class.forName(classValue); // 2. Create an object through reflection (parse the type with a string and create an object of this type) return (UserDao)clazz.newInstance(); //3. Convert the generated object to the strong object type } }
BeanFactory interface of IOC
- The IOC idea is based on the IOC container, and the bottom layer of the IOC container is the object factory
- The IOC container provided by Spring can be implemented in two ways (two interfaces)
(1) BeanFactory: the basic implementation of IOC container, which is the internal use interface of Spring and is not provided to developers
- Objects are not created when the configuration file is loaded, but only when the object is obtained
(2) ApplicationContext: the sub interface of BeanFactory, which provides more and more powerful functions and is generally used by developers - When the configuration file is loaded, the object specified in the configuration file is created
- Time consuming and resource consuming operations are usually loaded at startup, so the second method is generally used
Ctrl + H in idea to view the interface implementation class of ApplicationContext:
IOC operation Bean management
concept
- Bean Management: Spring creates objects + injects attributes
- There are two ways to implement Bean Management:
- Implementation of configuration file based on xml
- Annotation based implementation
XML based approach
- XML create object
- XML injection properties
- XML injection other types of attributes
- XML injection collection properties
- XML: factorybean Bean scope Bean lifecycle
- XML auto assembly
- XML external properties file
IOC operation bean management - based on XML
Creating objects based on XML
<bean id="User" class="com.cherrychen.User"></bean>
(1) In the Spring configuration file, you can create objects by using bean tags and adding corresponding attributes in the tags
(2) There are many attributes in the bean tag:
*id: unique identification
*Class: class full path (package class path)
(3) When creating an object, the nonparametric construction method is executed by default to complete the object creation.
Attribute injection based on XML
Dependency Injection: Dependency Injection (injection attribute)
The first injection method: use the set method for injection
(1) Create classes and define properties and set methods
public class Book { // Create attribute private String bname; private String bauthor; //Create the set method corresponding to the attribute public void setBname(String bname) { this.bname = bname; } public void setBauthor(String bauthor) { this.bauthor = bauthor; } // The get method is used for testing public String getBname() { return bname; } public String getBauthor() { return bauthor; } }
(2) Create a new spring configuration file bean XML, configuration object creation, configuration attribute injection
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 2. set Method injection properties --> <!-- to configure Book object --> <bean id="book" class="com.cherrychen2.Book"> <!--use property Complete attribute injection name: The name of the attribute in the class value: Values injected into attributes --> <property name="bname" value="Big talk design mode"> </property> <property name="bauthor" value="Data structure budget method"></property> </bean> </beans>
(3) Testing
public class IOCTest { @Test public void test(){ //1. Get profile ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml"); Book book = context.getBean("book", Book.class); System.out.println(book.getBauthor()); System.out.println(book.getBname()); } }
Test results:
The second injection method: use parametric structure for injection
(1) Create a class and define an attribute. The created attribute corresponds to a parameter construction method
public class Orders { //attribute private String oname; private String address; //Parametric structure public Orders(String oname, String address) { this.oname = oname; this.address = address; } //The get method is used for testing public String getOname() { return oname; } public String getAddress() { return address; } }
(2) Configure in the Spring configuration file
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 3 Injection attribute with parameter construction --> <bean id="orders" class="com.cherrychen2.Orders"> <constructor-arg name="oname" value="MacbookPro"></constructor-arg> <constructor-arg name="address" value="China"></constructor-arg> </bean> </beans>
(3) Testing
public class IOCTest { @Test public void test2(){ //1. Get profile ApplicationContext context= new ClassPathXmlApplicationContext("beanOrder.xml"); //2. Create object Orders orders = context.getBean("orders", Orders.class); System.out.println(orders); } }
test result
p namespace injection: Using p namespace injection can simplify xml configuration
Step 1: add the P namespace in the configuration file xmlns: P=“ http://www.springframework.org/schema/p "
Step 2: conduct attribute injection and operate in the bean tag
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 2. set Method injection properties --> <!-- p Namespace injection --> <bean id="book" class="com.cherrychen2.Book" p:bname="data structure" p:bauthor="anonymous person"></bean> </beans>
xml injection other types of attributes
Literal
(1) null value
<!--null--> <property name="address"> <null/> </property>
(2) Attribute values contain special symbols
<!--Attribute values include special symbols 1. hold<>Escape:< > 2. Write content with special symbols to CDATA --> <property name="address"> <value><![CDATA[<<Cherry>>]]></value> </property>
Injection properties: external bean s
1. Create two classes: service and dao
2. method of calling dao in service class
3. Configure in the Spring configuration file
/** * UserDao Interface */ public interface UserDao { void update(); } /** * UserDao Implementation class of interface */ public class UserDaoImpl implements UserDao{ @Override public void update() { System.out.println("DAO: updating..."); } } /** * UserService class containing UserDao class */ public class UserService { // Create UserDao type attribute and generate set method private UserDao userDao; public void setUserDao(UserDaoImpl userDao) { this.userDao = userDao; } public void add(){ System.out.println("service...+++"); userDao.update(); } }
Configure in xml file:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 1. establish service and dao object --> <bean id="userService" class="com.cherrychen2.UserService"> <!-- injection userDao object name: Attribute name in class ref: establish userDao object bean Tagged id value--> <property name="userDao" ref="userDaoImpl"></property> </bean> <bean id="userDaoImpl" class="com.cherrychen2.UserDaoImpl"></bean> </beans>
Injection properties - internal bean s
(1) One to many relationships: departments and employees
A department has multiple employees, and one employee belongs to one department
The Department is one, and there are many employees
(2) One to many relationships are represented between entity classes. Employees represent their departments and are represented by object type attributes
//Department category public class Dept { private String dname; public void setDname(String dname) { this.dname = dname; } } //Employee category public class Employee { private String ename; private String gender; //Employees belong to a department. Use object representation private Dept dept; //set method public void setEname(String ename) { this.ename = ename; } public void setGender(String gender) { this.gender = gender; } public void setDept(Dept dept) { this.dept = dept; } }
(3) Configure in the Spring configuration file
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- inside bean --> <bean id="employee" class="com.cherrychen3.Employee"> <!--Set two common properties--> <property name="ename" value="Cherry Chen"></property> <property name="gender" value="female"></property> <!--Set object type properties--> <property name="dept"> <bean id="dept" class="com.cherrychen3.Dept"> <property name="dname" value="IT department"></property> </bean> </property> </bean> </beans>
Injection attribute: cascade assignment
The first method is to set attribute values in multiple entity classes
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- Cascade assignment --> <bean id="employee" class="com.cherrychen3.Employee"> <!--Set two common properties--> <property name="ename" value="Cherry Chen"></property> <property name="gender" value="female"></property> <!--Set object type properties--> <property name="dept" ref="dept"></property> </bean> <bean id="dept" class="com.cherrychen3.Dept"> <property name="dname" value="IT department"></property> </bean> </beans>
The second method is to generate the get method of the internal bean class
In the original bean, the attribute can be modified by dept.dname.
XML injection collection properties
(1) Create classes, define array, list, map and set type attributes, and generate corresponding set methods
public class Student { // 1. Array type attribute private String[] courses; // 2. list collection type attribute private List<String> list; // 3. map collection type attribute private Map<String, String> maps; // 4. set collection type attribute private Set<String> sets; //set method public void setCourses(String[] courses) { this.courses = courses; } public void setList(List<String> list) { this.list = list; } public void setMaps(Map<String, String> maps) { this.maps = maps; } public void setSets(Set<String> sets) { this.sets = sets; } @Override public String toString() { return "Student{" + "courses=" + Arrays.toString(courses) + ", list=" + list + ", maps=" + maps + ", sets=" + sets + '}'; } }
(2) Configure in Spring configuration file
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="student" class="com.cherrychen3.Student"> <!-- Array type attribute injection --> <property name="courses"> <array> <value>Java curriculum</value> <value>C++curriculum</value> </array> </property> <!-- list Type attribute injection --> <property name="list"> <list> <value>Cherry</value> <value>Milanda</value> </list> </property> <!-- map Type attribute injection --> <property name="maps"> <map> <entry key="JAVA" value="java lang"></entry> <entry key="PHP" value="php"></entry> </map> </property> <!-- set Type attribute injection --> <property name="sets"> <set> <value>MongoDB</value> <value>MySQL</value> </set> </property> </bean> </beans>
Sets the object type value in the collection
<!-- Create multiple course object --> <bean id="course1" class="com.cherrychen3.Course"> <property name="cname" value="Spring5"></property> </bean> <bean id="course2" class="com.cherrychen3.Course"> <property name="cname" value="MyBatis"></property> </bean> <bean id="student" class="com.cherrychen3.Student"> <!-- list Type attribute injection --> <property name="courseList"> <list> <ref bean="course1"></ref> <ref bean="course2"></ref> </list> </property>
Extract the set injection part
(1) Introducing namespace util into Spring configuration file
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
(2) Using util tag to complete list collection injection and extraction
<util:list id="bookList"> <value>Data structure and algorithm</value> <value>a motley crew</value> <value>The neurotic personality of our time</value> </util:list> <!-- extract list Collection type attribute injection usage --> <bean id="book" class="com.cherrychen2.Book"> <property name="list" ref="bookList"></property> </bean>
FactoryBean
- Spring has two types of beans: ordinary beans and factory beans
- Ordinary bean: the bean type defined in the configuration file is the return type
- Factory bean: the bean type defined in the configuration file can be different from the return type
Step 1: create a class, make this class as a factory bean, and implement the interface FactoryBean
Step 2: implement the method in the interface and define the returned bean type in the implemented method
public class MyBean implements FactoryBean<Course> { //Returned bean definition @Override public Course getObject() throws Exception { Course course = new Course(); course.setCname("MySQL-course name"); return course; } @Override public Class<?> getObjectType() { return null; } @Override public boolean isSingleton() { return FactoryBean.super.isSingleton(); } }
Configuration in xml:
<bean id="myBean" class="com.cherrychen4.MyBean"></bean>
Test:
@Test public void test5(){ ApplicationContext context = new ClassPathXmlApplicationContext("beanfactory.xml"); Course course = context.getBean("myBean", Course.class); System.out.println(course); }
Test results:
Scope of bean
- In Spring, set whether to create a bean instance as a single instance or multiple instances
- In Spring, bean s are singleton objects by default
- How to set single instance or multiple instances
(1) In the bean tag of Spring configuration file, there is a property (scope) to set single instance or multi instance
(2) scope property value
The first value: the default value, singleton, indicates a single instance object
The second value: prototype, which indicates that it is a multi instance object
bean.xml is changed to: < bean id = "book" class = "com. Cherrychen2. Book" scope = "prototype" P: bName = "data structure" p:bauthor = "anonymous" > < / bean >
The lifecycle of a bean
Lifecycle: the process of creating and destroying objects
Life cycle of the bean (without post processor)
- Create a bean instance through a parameterless constructor
- Set values for bean properties and references to other beans (call the set method)
- Call the initialization method of the bean (the method that needs configuration initialization)
- The bean is ready to use (the object is obtained)
- When the container is closed, the bean destruction method (the method that needs to be configured for destruction) is called
public class Orders { private String oname; public Orders() { System.out.println("The first step is to create a parameterless structure bean example"); } public void setOname(String oname) { this.oname = oname; System.out.println("Step 2 call set Method to set the property value"); } //Method for creating and executing initialization public void initMethod(){ System.out.println("Step 3: execute initialization method"); } //Method for creating and executing destruction public void destroyMethod(){ System.out.println("Step 5: execute the destruction method"); } }
XML configuration:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="orders" class="com.cherrychen4.Orders" init-method="initMethod" destroy-method="destroyMethod"> <property name="oname" value="mobile phone"></property> </bean> </beans>
Test:
@Test public void test7(){ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beanOrder.xml"); var orders = context.getBean("orders", com.cherrychen4.Orders.class); System.out.println("Step 4: get and create bean Instance object"); System.out.println(orders); //Manually destroy the bean instance context.close(); // . close() calls destroy method }
test result
bean life cycle (with post processor)
- Create a bean instance through a parameterless constructor
- Set values for bean properties and references to other beans (call the set method)
- The method of passing the bean instance to the bean post processor postProcessBeforeInitialization
- Call the initialization method of the bean (the method that needs configuration initialization)
- The method of passing the bean instance to the bean post processor postProcessAfterInitialization
- The bean is ready to use (the object is obtained)
- When the container is closed, the bean destruction method (the method that needs to be configured for destruction) is called
public class MyBeanPost implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { System.out.println("Method executed before initialization"); return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println("Method executed after initialization"); return bean; } }
XML automatic assembly (less used, generally annotated)
What is automatic assembly: Spring automatically injects matching attribute values according to the specified assembly rules (attribute name or attribute type)
(1) Automatic injection according to attribute name
<!--Realize automatic assembly bean Label properties autowire,Configure automatic assembly autowire Attribute values usually have two values: byName Inject value according to attribute name bean of id The value is the same as the class attribute name byType Inject according to attribute type --> <bean id="Employee" class="com.cherrychen4.autowire.Employee" autowire="byName"></bean> <bean id="dept" class="com.cherrychen4.autowire.Dept"></bean>
External attribute files (such as database user permission authentication)
Method 1: directly configure database information
(1) Configure Druid connection pool
(2) Introducing Druid connection pool dependent jar package
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/userDb"></property> <property name="username" value="root"></property> <property name="password" value="root"></property> </bean>
Method 2: introduce an external property file to configure the database connection pool
(1) Create external property files, properties format files, and write database information
(2) Import the external properties property file into the Spring configuration file
- Introduce context namespace
xmlns:util="http://www.springframework.org/schema/util"
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" >
- In the Spring configuration file, the tag is used to import the external property file, and the value is set in the way of ${xxx}
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${prop.driverClassName}"></property> <property name="url" value="${prop.url}"></property> <property name="username" value="${prop.username}"></property> <property name="password" value="${prop.password}"></property> </bean>
IOC operation Bean management - annotation based
- What is annotation
- Annotation is a special mark of code. Format: @ annotation name (attribute name = attribute value, attribute name = attribute value,...)
- Use annotations, which act on classes, methods and attributes
- Purpose of using annotations: to simplify xml configuration
- Spring provides annotations for creating objects in bean Management:
- @Component
- @Service
- @Controller
- @Repository
The functions of the above four annotations are the same and can be used to create bean instances.
- Object creation based on annotation
Step 1: introduce the jar package: spring-aop-5.2.6 RELEASE. jar
Step 2: start annotation scanning
<!-- Turn on component scanning 1,If multiple packages are scanned, the package names are separated by commas "com.cherry.dao, com.chery.service" 2,Scan package upper directory --> <context:component-scan base-package="com.cherrychen4"/>
Step 3: create a class and add the annotation of [create object] on the class
@Component(value = "userService") // <bean id="userService" class="..."> public class UserService { // Create UserDao type attribute private UserDao userDao; public void add(){ System.out.println("service...+++"); userDao.update(); } }
Step 4: start the detailed configuration of component scanning
<!--include Indicates only scan@Controller, exclude Do not scan--> <context:component-scan base-package="com.cherrychen2" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
Step 5: implement attribute injection based on annotation
(1) @ Autowired: auto assemble according to attribute type
@Service(value = "userService") // <bean id="userService" class="..."> public class UserService { // Create UserDao type attribute // There is no need to add a set method // Add annotation for injection attribute @ autowired @Autowired private UserDao userDao; public void add(){ System.out.println("service...+++"); userDao.update(); } }
(2) @Qualifier: inject by name
Need to be used with @ Autowired
@Service(value = "userService") // <bean id="userService" class="..."> public class UserService { // Create UserDao type attribute // There is no need to add a set method // Add annotation for injection attribute @ autowired @Autowired //Injection according to type @Qualifier(value = "userDaoImpl1") //Inject according to the name and put it into different implementation classes private UserDao userDao; public void add(){ System.out.println("service...+++"); userDao.update(); } }
(3) @ Resource: can be injected according to type or name * * [based on javax, not recommended]**
public class UserService { @Resource //Injection according to type @Resource(value = "userDaoImpl1") //Inject according to the name and put it into different implementation classes private UserDao userDao; public void add(){ System.out.println("service...+++"); userDao.update(); } }
(4) @ Value: inject common type attribute
@Value(value = "abc") private String name;
Fully annotated development
(1) Create configuration class instead of xml file
@Configuration //As a configuration class, replace the xml file @ComponentScan(basePackages = {"com.cherrychen"}) public class SpringConfig{ }
(2) Write test class
@Test public void test8(){ //Load configuration class ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); UserService userService = context.getBean("userService", UserService.class); System.out.println(userService); userService.add(); }