A Brief Introduction to Spring
—— Configuration of IOC containers and beans
Introduction to Spring
Spring is an open source framework as well as an IOC and AOP container framework.
Sprin characteristics
Non-intrusive: Objects in Spring-based applications can be independent of Spring API s.
(2) Dependency injection: DI-Dependency Injection, the most classic implementation of Inversion Control (IOC).
Aspect Oriented Programming - AOP.
Container: Spring is a container because it contains and manages the declaration cycle of application objects.
Componentization: Spring implements the combination of simple component configurations into a complex application, which can be combined with XML and Java annotations in Spring.
One-stop: On the basis of IOC and AOP, we can integrate various open source frameworks and excellent third-party libraries for enterprise applications.
Spring module
Build Spring Runtime Environment
- Join the JAR package (five jars must be imported first)
Spring's own JAR package: spring-framework-4.0.0. RELEASE LIBS directory
- spring-beans-4.0.0.RELEASE.jar
- spring-context-4.0.0.RELE2ASE.jar
- spring-core-4.0.0.RELEASE.jar
- spring-expression-4.0.0.RELEASE.jar
② commons-logging-1.1.1.jar
- Create Spring configuration file in Spring Tool Suite tool by following steps
① File->New->Spring Bean Configuration File
(2) Name the file, e.g. applicationContext.xml
IOC container
IOC(Inversion of Control): Inversion of control, IOC container is essentially an object factory at the bottom.
The idea of inversion control completely overturns the traditional way of resource acquisition for application components: reversing the direction of resource acquisition, instead of pushing resources to the required components by the container, developers do not need to know how the container creates resource objects, they only need to provide a way to receive resources, which is enormous. It reduces the cost of learning and improves the efficiency of development. This behavior is also known as the passive form of search.
DI(Dependency Injection): Dependency Injection
IOC is an idea of inversion control, and DI is a concrete implementation of IOC.
Implementation of IOC Container in Spring
1) The IOC container itself needs to be instantiated before the Bean's'instance can be read through the IOC container.
2) Spring provides two implementations of IOC container
BeanFactory: The basic implementation of IOC container is Spring's internal infrastructure, which is oriented to Spring itself, not for developers.
(2) Application Context: BeanFactory's sub-interface provides more advanced features. For Spring users, Application Context is used in almost all situations, rather than the underlying BeanFactory.
Main Implementation Classes of ApplicationContext
-
ClassPath Xml Application Context: Configuration file in XML format under the corresponding classpath
-
FileSystem Xml Application Context: Configuration file in XML format in the corresponding file system
-
A single bean is created at initialization, or it can be configured to specify that the created bean is multi-instance.
Attribute assignment of bean s
(1) Dependency Injection
A. Assignment through the bean's setXxx() method (most commonly used)
Create an Employee class
package bean; public class Employee { private Integer id; private String name; private String desc; public Employee(Integer id, String name, String desc) { super(); this.id = id; this.name = name; this.desc = desc; } public Employee() { super(); System.out.println("The parametric constructor was called"); } public Integer getId() { return id; } public void setId(Integer id) { System.out.println("setId"); this.id = id; } public String getName() { return name; } public void setName(String name) { System.out.println("setName"); this.name = name; } public String getDesc() { return desc; } public void setDesc(String desc) { System.out.println("setDesc"); this.desc = desc; } @Override public String toString() { return "Employee [id=" + id + ", name=" + name + ", desc=" + desc + "]"; } }
Create configuration file XML
<bean id="employee01" class="bean.Employee"> The XXX in name= "xxxx" is either set casually or lowercase the setXxx() method name in bean.Employee, such as xxx, value is set by itself, similar to the value initialized by the constructor. > <property name="id" value="1001" ></property> <property name="name" value="Zhang San">property> <property name="desc" value="good man 1"> </property> </bean>
Create test classes
package test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import bean.Employee; public class Test01 { public static void main(String[] args) { /*Creating Spring container objects, when creating container objects, will read the spring configuration file, from the configuration file, you can know that the current container manages the creation of those objects, while the container manages the object to be created.*/ ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml"); // Getting employees from Spring container objects Employee employee = context.getBean("employee01", Employee.class); System.out.println(employee); }
Implementation results:
The parametric constructor was called setId setName setDesc Employee [id=1001, name = Zhang San, desc = Good Man 1]
B. Assignment through the bean's constructor (understand)
1) Matching by the name of the parameter in the constructor
The rest of the Employee class remains unchanged, with parametric constructions as follows:
public Employee(Integer id, String name, String desc) { super(); System.out.println("The parametric construct is called"); this.id = id; this.name = name; this.desc = desc; }
Change the configuration file XML to read as follows:
<bean id="employee02" class="bean.Employee"> <constructor-arg name="id" value="1002"></constructor-arg> <constructor-arg name="name" value="Li Si"></constructor-arg> <constructor-arg name="desc" value="Good Man 2"></constructor-arg> </bean>
Implementation results:
The parametric construct is called // and the set() method is not called at this time Employee [id=1002, name = Li Si, desc = Good Man 2]
2) Specify parameter location by index value
The Employee class remains unchanged, just changing the configuration file:
<bean id="employee03" class="bean.Employee"> <constructor-arg index="0" value="1003"></constructor-arg> <constructor-arg index="1" value="Wang Wu"></constructor-arg> <constructor-arg index="2" value="Good Man 3"></constructor-arg> </bean>
Implementation results:
The parametric construct is called Employee [id=1003, name = Wang Wu, desc = Good Man 3]
3) Spring automatically matches the appropriate constructor
Automatically matching the appropriate constructor requires that the parameter type passed must be consistent with the parameter type of the constructor!
The Employee class remains unchanged, just changing the configuration file:
<bean id="employee04" class="bean.Employee"> <constructor-arg value="1004"></constructor-arg> <constructor-arg value="Money six"></constructor-arg> <constructor-arg value="Good Man 4"></constructor-arg> </bean>
Implementation results:
The parametric construct is called Employee [id=1004, name = Qian 6, desc = Good Man 4]
4) Distinguishing overloaded constructors by type
Add the salary attribute of Double type to the Employee class, other attributes remain unchanged, and provide get/set method and toString method to provide a new constructor, which does not require desc.
package bean; public class Employee { private Integer id; private String name; private String desc; private Double salary; public Employee(Integer id, String name, String desc) { super(); this.id = id; this.name = name; this.desc = desc; } public Employee(Integer id, String name, Double salary) { super(); this.id = id; this.name = name; this.salary = salary; } public Employee() { super(); // TODO Auto-generated constructor stub } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public Double getSalary() { return salary; } public void setSalary(Double salary) { this.salary = salary; } @Override public String toString() { return "Employee [id=" + id + ", name=" + name + ", desc=" + desc + ", salary=" + salary + "]"; } }
Change the configuration file:
<bean id="employee05" class="bean.Employee"> <constructor-arg value="1005"></constructor-arg> <constructor-arg value="Feng 7"></constructor-arg> <constructor-arg value="10000"></constructor-arg> </bean>
results of enforcement
Employee [id=1005, name=Feng7, desc=10000, salary=null]//When there are two constructors, the constructor that receives String type and Double type parameter should be called before, because when reflecting all constructors in the class, the bottom layer is placed in an array. If the first one in the array can match, then the latter one will not match.
Ergodic constructor:
public static void main(String[] args){ testConstructor(); } public static void testConstructor() { Class cla = Employee.class; Constructor[] cons = cla.getDeclaredConstructors(); for (Constructor constructor : cons) { System.out.println(constructor); } }
The results are as follows:
public bean.Employee(java.lang.Integer,java.lang.String,java.lang.String) public bean.Employee(java.lang.Integer,java.lang.String,java.lang.Double) public bean.Employee()
Solution to the problem: Setting type in xml file
<bean id="employee05" class="bean.Employee"> <constructor-arg value="1005"></constructor-arg> <constructor-arg value="Feng 7"></constructor-arg> <constructor-arg value="10000" type="java.lang.Double"></constructor-arg> </bean>
The results are as follows:
Employee [id=1006, name=Feng Qi,salary=10000.0]
Literal
-
Values that can be represented by strings can be specified by value attributes or value subnodes.
-
Basic data types, encapsulation classes, String and other types can be injected literally.
-
If the literal value contains special characters, you can wrap the literal value with <![CDATA[]]>.
Create a Book class
package bean; public class Book { private String isbn; private String name; public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Book [isbn=" + isbn + ", name=" + name + "]"; } }
Configuration in spring_ioc.xml file
<bean id="book01" class="bean.Book"> <!--adopt value Attribute assignment--> <property name="isbn" value="j001"></property> <property name="name" value="Alive"></property> </bean> ------------------------------------------------------------------------------------- <bean id="book02" class="bean.Book"> <!--adopt value Label assignment--> <property name="isbn"> <value>j001</value> </property> <property name="name"> <value>Alive</value> </property> </bean> ------------------------------------------------------------- <bean id="book03" class="bean.Book"> <!--adopt value Label assignment, can omit the label body, directly with“/"End--> <property name="isbn" value="j001"/> <property name="name" value="Alive"/> </bean> <!--If there are special characters that can be escaped by entities, they can also be placed in<![CDATA[]]Medium,<![CDATA[]]Out of commission value Attribute, can only be used value Label--> <property name="name"> <value> <![CDATA[!@#Programming Thoughts]> ____________ </value> </property>
Reference to other bean s
Create Employee and Department classes for employees
package bean; public class Employee { private Integer id; private String name; private String desc; private Double salary; private Department dept; public Employee(Integer id, String name, String desc, Double salary, Department dept) { super(); this.id = id; this.name = name; this.desc = desc; this.salary = salary; this.dept = dept; } public Employee() { super(); // TODO Auto-generated constructor stub } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public Double getSalary() { return salary; } public void setSalary(Double salary) { this.salary = salary; } public Department getDept() { return dept; } public void setDept(Department dept) { this.dept = dept; } @Override public String toString() { return "Employee [id=" + id + ", name=" + name + ", desc=" + desc + ", salary=" + salary + ", dept=" + dept + "]"; } }
package bean; public class Department { private Integer id; private String name; public Department() { super(); // TODO Auto-generated constructor stub } public Department(Integer id, String name) { super(); this.id = id; this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Department [id=" + id + ", name=" + name + "]"; } }
Configure Department attributes in 12.xml file
<bean id="employee01" class="bean.Employee"> <property name="id" value="1006"></property> <property name="name" value="Zhang Sanfeng"></property> <property name="desc" value="staff"></property> <property name="salary" value="1500"></property> <property name="dept" ref="dept"></property> </bean> <bean id="dept" class="bean.Department"> <property name="id" value="200"></property> <property name="name" value="Wudang Mountain"></property> </bean> </beans>
Test class
package test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import bean.Employee; public class Test03 { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("12.xml"); Employee employee01 = context.getBean("employee01", Employee.class); System.out.println(employee01); } }
Result:
Employee [id=1006, name = Zhang Sanfeng, desc = employees, salary=1500.0, dept=Department [id=200, name = Wudang Mountain]]
Assignment of cascading attributes to bean s
<bean id="employee02" class="bean.Employee"> <property name="id" value="1007"></property> <property name="name" value="Zhang Feng"></property> <property name="desc" value="Employee 02"></property> <property name="salary" value="15002"></property> <property name="dept" ref="dept"></property> <!--Cascaded attribute operations--> <property name="dept.name" value="Emei School"></property> </bean> <bean id="dept" class="bean.Department"> <property name="id" value="200"></property> <property name="name" value="Wudang Mountain"></property> </bean>
Result:
Employee [id=1007, name = Zhangfeng, desc = employees 02, salary=15002.0, dept=Department [id=200, name = Emei faction]]