directory
  • Spring-ioc container -Bean management – XML-based
    • Overview of the Spring Framework
    • IOC concepts and principles
    • IOC operation Bean management (injection in set mode && injection using a parameterized construct)
    • IOC operation Bean management (XML injection of other types of attributes)
    • IOC operation Bean Management (XML injection collection attributes)
    • IOC Operation Bean Management (FactoryBean)
    • IOC operation Bean Management (Bean scope)
    • IOC operation Bean Management (Bean life cycle)Juejin. Cn/post / 702106…
    • IOC operation Bean Management (XML autowiring)
    • IOC operation Bean Management (external properties file)

Spring-ioc container -Bean management – XML-based

Overview of the Spring Framework

1.Spring is a lightweight open source JavaEE framework

2.Spring solves the complexity of enterprise application development

3.Spring has two core parts: IOC and AOP

IOC: Inversion of control, turn over the object creation process to Spring for management.AOP: section-oriented, without modifying the source code for functional enhancementCopy the code

4. The characteristics of the Spring

Easy decoupling, simplified development 2.AOP programming support 3. Easy program testing 4. Easy to integrate with other frameworksCopy the code

5. Facilitate transaction operations

6. Make API development easier

IOC concepts and principles

1. What is IOC?

1. Inversion of control, the object creation and call process between objects is handed over to Spring for management. 2Copy the code

2. Basic principles of IOC

XML parsing, factory schema, reflectionCopy the code

3. Diagram underlying principles of IOC

4.IOC (BeanFactory interface)

2.Spring provides two ways to implement the IOC container: (two interfaces) The IOC container is a basic implementation of Spring's internal use interface, which does not provide developers to use the load configuration file will not create objects, after obtaining objects (use) to create objects. BeanFactory subinterface, provides more and more powerful functions, provided for developers to use (loading the configuration file will be created in the configuration file object) recommended use!Copy the code

5.IOC operation Bean management

1. What is Bean management? Bean management refers to two operations: 1.Spring creates objects 2.Spring injects properties 2. Implementation based on XML configuration files 2. Implementation based on annotationsCopy the code

The following sections detail the XML-based approach to IOC operation Bean management

IOC operation Bean management (injection in set mode && injection using a parameterized construct)

1. Injection in set mode

① Create a class and define attributes and corresponding set methodsCopy the code
public class Book { private String bName; private String bAuthor; Public void setbName(String bName) {this.bName = bName; } public void setbAuthor(String bAuthor) {this.bauthor = bAuthor; }}Copy the code
② Configure object creation and property injection in the Spring configuration fileCopy the code
<! - using the set method injection properties - > < bean id = "book" class = "com. Atguigu. Spring5. TestDemo. Book" > <! Name: the name of the property in the class value: <property name="bAuthor" value=" bAuthor" ></property> <property name="bName" value=" bAuthor" ></property>Copy the code

2. Use parameterized constructs for injection

① Create class, define attribute, create attribute pair should have parameter constructorCopy the code
public class Order { private String oName; private String address; public Order(String oName, String address) { this.oName = oName; this.address = address; }}Copy the code
② Perform the configuration in the Spring configuration fileCopy the code
<! - parameter structure injection properties - > < bean id = "order" class = "com. Atguigu. Spring5. TestDemo. Order" > < constructor - arg name = "address" /> <constructor-arg name="oName" /> </bean>Copy the code

IOC operation Bean management (XML injection of other types of attributes)

1. Inject null values and special symbols

<bean id="book" class="com.atguigu.spring5.Book"> <! -- (1) null --> <property name="address"> <null/><! Add a null tag to the property --> </property> <! -- (2) special symbol assignment --> <! -- The attribute value contains the special symbol a to escape <>. &gt; CDATA --> <property name="address"> <value><! [CDATA[<< nanjing >>]]></value> </property> </bean>Copy the code

2. Inject properties – external beans

① Create two classes service and DAOCopy the code
Public class UserDao {//service class // Create UserDao type attribute, generate set method private UserDao UserDao; public void setUserDao(UserDao userDao) { this.userDao = userDao; } public void add() { System.out.println("service add..............." ); userDao.update(); Public class UserDaoImpl implements UserDao {//dao class @override public void update() { System.out.println("dao update..........." ); }}Copy the code
② Perform the configuration in the Spring configuration fileCopy the code
<! - 1 service and the dao object creation - > < bean id = "userService" class = "com. Atguigu. Spring5. Service. UserService" > <! Insert userDao into userDao <property name="userDao" ref="userDaoImpl"></property> </bean> <bean ID ="userDaoImpl" class="com.atguigu.spring5.dao.UserDaoImpl"></bean>Copy the code

Inject properties – inner beans

(1) One-to-many relationship is represented between entity classes. Employees represent their departments and are represented by object type attributesCopy the code
Public class Dept {private String dname; public void setDname(String dname) { this.dname = dname; Public class Emp {private String ename; private String gender; // Employees belong to a certain department. Private Dept Dept; public void setDept(Dept dept) { this.dept = dept; } public void setEname(String ename) { this.ename = ename; } public void setGender(String gender) { this.gender = gender; }}Copy the code

② In the Spring configuration file

<! - internal bean - > < bean id = "emp" class = "com. Atguigu. Spring5. Bean. The emp" > <! Property name="ename" value=" jay "></property> <property name="gender" value=" male "></property> <! - set object type properties - > < property name = "dept" > < bean id = "dept" class = "com. Atguigu. Spring5. Beans. Dept" > <! </property> </bean> </property> </bean>Copy the code

Injection properties – Cascade assignments

<! One - way: cascade assignment - > < bean id = "emp" class = "com. Atguigu. Spring5. Bean. The emp" > <! <property name="ename" value="Andy"></property> <property name="gender" value=" female "></property> <! - cascade assignment - > < property name = "dept" ref = "dept" > < / property > < / bean > < bean id = "dept" class = "com. Atguigu. Spring5. Beans. Dept" > <property name="dname" value=" pr department "></property> </bean>Copy the code
// Create dept get method (get method must have!!) public Dept getDept() { return dept; }Copy the code
<! - cascade assignment - > < bean id = "emp" class = "com. Atguigu. Spring5. Bean. The emp" > <! <property name="ename" value="jams"></property> <property name="gender" value=" male "></property> <! Property name="dept" ref="dept"></property> <property name="dept" value=" dept"></property> </bean> <bean id="dept" class="com.atguigu.spring5.bean.Dept"> </bean>Copy the code

IOC operation Bean Management (XML injection collection attributes)

1. XML injects array type attributes

2. XML injects the List collection type attribute

3. XML injects Map collection type attributes

Public class Stu {//1 private String[] courses; Private list <String> list; private list <String> list; //3 Map collection type attribute private map <String,String> maps; Private set <String> sets; private set <String> sets; public void setSets(Set<String> sets) { this.sets = sets; } 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; }Copy the code
<! - (2) in the spring configuration file to configure - > < bean id = "stu" class = "com. Atguigu. Spring5. Collectiontype. Stu" > <! --> <property name="courses"> <array> <value> <value> <value> <value> <value> --> <property name="list"> <list> <value> <value> <value> <value> <value> </value> </list> </property> <! <property name="maps"> <map> <entry key="JAVA" value=" JAVA" ></entry> <entry key="PHP" value="php"></entry> </map> </property> <! Property name="set "> <set> <value>MySQL</value> <value>Redis</value> </set> </property> </bean>Copy the code

Set the object type value in the collection

Private List<Course> courseList; Public void setCourseList(List<Course> courseList) {this.courseList = courseList; }Copy the code
<! - create multiple course object - > < bean id = "course1" class = "com. Atguigu. Spring5. Collectiontype. Course" > < property name = "cname" Value = "Spring5 framework >" < / property > < / bean > < bean id = "course2" class = "com. Atguigu. Spring5. Collectiontype. Course" > < property Name ="cname" value="MyBatis framework "></property> </bean> <! Insert the list collection type, Value is object --> <property name="courseList"> <list> <ref bean="course1"></ref> <ref bean="course2"></ref> </list> </property>Copy the code
<! -- Step 1: introduce the namespace util in the Spring configuration file. The 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:util="http://www.springframework.org/schema/util" <! - add util namespace -- > xsi: schemaLocation = "HTTP: / / 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"> <! Add util namespace --> <! The util tag is used to extract the list collection. Extract the collection injection part --> <! <util:list id="bookList"> <value> <value> <value> <value> </value> <value> </value> </value> </util:list> <! - 2 to extract the list collection type attributes inject use - > < bean id = "book" class = "com. Atguigu. Spring5. Collectiontype. The book" the scope = "prototype" > < property name="list" ref="bookList"></property> </bean>Copy the code

IOC Operation Bean Management (FactoryBean)

1.Spring has two types of beans, a normal bean and a FactoryBean.

2. Plain beans: Define the bean type as the return type in the configuration file

3. Factory Beans: Define bean types in configuration files that are different from return types

(1) create a class that acts as a FactoryBean and implements the interface FactoryBean.

(2) The second step to implement the interface inside the method, in the implementation of the method to define the return bean type.

Public class MyBean implements FactoryBean<Course> {MyBean @override public Course getObject() throws Exception { Course course = new Course(); course.setCname("abc"); return course; }}Copy the code
<bean id="myBean" class="com.atguigu.spring5.factorybean.MyBean">
</bean>
Copy the code
@Test public void test3() { ApplicationContext context = new ClassPathXmlApplicationContext("bean3.xml"); Course course = context.getBean("myBean", Course.class); // Return value type may not be the defined bean type! System.out.println(course); }Copy the code

IOC operation Bean Management (Bean scope)

In Spring, beans are singleton objects by default. Here’s how to set the scope:

1. In the Spring configuration file bean tag there is a property (scope) to set single-instance or multi-instance.

2. The scope attribute values

1. The first value: the default, singleton, indicates a singleton object. 2. The second value, prototype, indicates a multi-instance object.Copy the code
<bean id="book" class="com.atguigu.spring5.collectiontype.Book" scope="prototype"><! <property name=" bookList"></property> </bean>Copy the code

3. Singleton and Prototype

1. Singleton (prototype) 2. When scope is set to singleton, the spring configuration file is loaded to create a singleton. When setting scope to prototype, instead of creating an object when loading the Spring configuration file, create a multi-instance object when calling the getBean method.Copy the code

IOC operation Bean Management (Bean life cycle)

1. Lifecycle: The process from object creation to object destruction.

2. Bean life cycle

(1) Create bean instance through constructor (no argument construction) (2) set value for bean properties and reference to other beans (call set method) (3) Call bean initialization method (need configuration initialization method) (4) Bean ready to use (object fetch) ⑤ When the container is closed, call the bean's destruction method (the method that requires configuration destruction).Copy the code

3. Demonstrate the bean lifecycle

Public class Orders {// No argument constructor public Orders() {system.out.println (" first step -- execute no argument constructor to create bean instance "); } private String oname; public void setOname(String oname) { this.oname = oname; System.out.println(" Step 2 -- call the set method to set the property value "); } public void initMethod() {system.out.println (" step 3 -- perform the initialization method "); } public void destroyMethod() {system.out.println (" step 5 -- destroyMethod "); }}Copy the code
<bean id="orders" class="com.atguigu.spring5.bean.Orders" init-method="initMethod" destroy-method="destroyMethod"> <property name="oName" value=" oName" > </property> </bean>Copy the code
@Test public void test1(){ ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml"); Orders orders = context.getBean("orders", Orders.class); System.out.println(" Step 4 -- get create bean instance object "); System.out.println(orders); ((ClassPathXmlApplicationContext)context).close(); }Copy the code

Output: step 1 — create bean instance with no-argument construction step 2 — call set method to set property value step 3 — perform initialization method step 4 — get create bean instance object

4. Bean post-processor, bean life cycle has seven steps

(1) through the constructor to create the bean instance parameter structure (no) (2) for bean attribute set value and reference to other beans set method (call) (3) pass bean instance bean postProcessBeforeInitialization post processor (4) call the bean's initialization method (requires configuration initialization method) (5) method of rear pass bean instance bean processors postProcessAfterInitialization 6 bean can be used for capturing the (object) all landowners when closed container, Call the bean's destruction method (the method that requires configuration destruction)Copy the code

5. Demonstrate the effect of adding a rear processor

(1) Create a class to implement the interface BeanPostProcessor and create a post-processor.

Public class MyBeanPost implements BeanPostProcessor {public class MyBeanPost implements BeanPostProcessor PostProcessBeforeInitialization (Object beans, String beanName) throws BeansException {System. Out. Println (" before initialization method of execution ");  return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {system.out.println (" method executed after initialization "); return bean; }}Copy the code
<! - the bean parameters configuration file - > < bean id = "orders" class = "com. Atguigu. Spring5. Beans. The orders" init - method = "initMethod" destroy-method="destroyMethod"> <! <property name="oname" value=" phone "></property><! </bean> <! Rear - configuration processor - > < bean id = "myBeanPost" class = "com. Atguigu. Spring5. Beans. MyBeanPost" > < / bean >Copy the code

IOC operation Bean Management (XML autowiring)

1. What is automatic assembly?

Spring automatically annotates the matched property values based on the specified assembly rule (property name or property type)Copy the code

2. Demonstrate the automatic assembly process

① Automatic injection based on the attribute name

<! Autowire = autowire; autowire = autowire; ByName is injected based on the attribute name, Into the value of the bean id value as well as class attribute name byType injection - depending on the type of attribute > < bean id = "emp" class = "com. Atguigu. Spring5. Autowire. Emp" autowire = "byName" > </bean> <bean id="dept" class="com.atguigu.spring5.autowire.Dept"></bean>Copy the code

② Automatic injection according to the attribute type

<bean id="emp" class="com.atguigu.spring5.autowire.Emp" autowire="byType">
</bean>
<bean id="dept" class="com.atguigu.spring5.autowire.Dept"></bean>
Copy the code

IOC operation Bean Management (external properties file)

1. Configure the database information

1 Configure a Druid connection pool. The Druid connection pool depends on jar packages.Copy the code
<! - direct connection pool - > < 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>Copy the code

Import an external properties file to configure the database connection pool

Create external properties file, properties format file, write database information (jdbc.properties)Copy the code
prop.driverClass=com.mysql.jdbc.Driver
prop.url=jdbc:mysql://localhost:3306/userDb
prop.userName=root
prop.password=root
Copy the code
② Introduce the external properties property file into the Spring configuration file -- introduce the context namespace.Copy the code
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/context http://www.springframework.org/schema/context/spring-context.xsd"><! -- Introducing the context namespace --> <! - the introduction of external properties file - > < context: the property - placeholder location = "classpath: JDBC. Properties" / > <! - configure the connection pool - > < bean id = "dataSource" class = "com. Alibaba. Druid. Pool. DruidDataSource" > < property name = "driverClassName." value="${prop.driverClass}"></property> <property name="url" value="${prop.url}"></property> <property name="username" value="${prop.userName}"></property> <property name="password" value="${prop.password}"></property> </bean> </beans>Copy the code