IOCSingleton mode –Bean
SpringThe bean in China is determined by scope.
scopeThere are 4 types:
1.singleton:The singleton model indicates that the object obtained through the Spring container is unique.Commonly used and defaults.
2.prototype:Multiple-instance model, which means that objects retrieved through the Spring container are different (similar to the unique object address of new in Java infrastructure).
3.reqeust:The request indicates that it is valid in a HTTP request.
4.session:Session, which is valid in a user session.
1.Create an object
public class User { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
2.Instantiate User in the L configuration file of spring.
<?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"> <bean id="user" class="com.test.entity.User"> <property name="id" value="1"></property> <property name="name" value="User1"></property> </bean> </beans>
3.The test class gets two User instantiated objects through the Spring container and determines whether they are the same object by the == method.
public class Test { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); User u1 = (User) applicationContext.getBean("user"); User u2 = (User) applicationContext.getBean("user"); System.out.println(u1 == u2); } }
Summary: Seeing the result print true indicates that user1 and user2 are the same object, so the default value of scope is singleton (singleton mode), which means that objects created with spring are singletons.
Code for multiple case mode
<?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"> <bean id="user" class="com.test.entity.User" scope="prototype"> <property name="id" value="2"></property> <property name="name" value="User2"></property> </bean> </beans>
SpringInheritance
SpringUnlike Java inheritance, a child bean can inherit attributes in a parent bean in the same way as a parent bean.
If the child bean inherits the parent bean and the sub bean assigns the attribute to the attribute, the value of the parent bean will be overwritten.
<?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"> <bean id="user" class="com.test.entity.User"> <property name="id" value="1"></property> <property name="name" value="Zhang San 1 "></property> </bean> <bean id="user2" class="com.test.entity.User" parent="user"> <!-- Overwrite the name attribute value of user.--> <property name="name" value="Zhang San 2 "></property> </bean>
</beans>
SpringDependence
Similar to inheritance, dependencies are a way of associating beans with beans. After configuring dependencies, the dependent beans must be created first, and then the dependent beans.
The keyword used is depends-on= “the ID of the bean being dependent”.
<?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"> <!-- userDepend on car--> <bean id="user" class="com.test.entity.User" depends-on="car"> <property name="id" value="1"></property> <property name="name" value="Zhang three "></property> </bean> <bean id="car" class="com.test.entity.Car"> <property name="id" value="1"></property> <property name="brand" value="BMW "></property> </bean> </beans>
The execution sequence of these codes is: car–> user. First create car, then create user.
SpringRead external resources.
In development, files like databases are saved in a properties file for easy maintenance, so using Spring requires reading data source objects.
1.First create a peoperties file under the path, the specific location is placed according to project requirements.
##key==valueForm
driverName = com.mysql.jdbc.Driver url = jdbc:mysql://localhost:3306/shop user = root pwd = root
2.springThe configuration data source is configured in the configuration file, and the C3P0 data source is used here.
<?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: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-4.0.xsd"> <!-- Import external resource files--> <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder> <!-- Create a data source, read the data in the resource file through ${}, fill in the key in ${}, the value in the name may be different according to the connection pool name, try to decompile the code to find the corresponding property name--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${user}"></property> <property name="password" value="${pwd}"></property> <property name="driverClass" value="${driverName}"></property> <property name="jdbcUrl" value="${url}"></property> </bean> </beans>
3.test
public class Test { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); DataSource ds = (DataSource) applicationContext.getBean("dataSource"); Connection conn = null; try { conn = ds.getConnection(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(conn); } }
IOCCreate objects through factory methods
SpringIOC is a typical factory mode, so how can we use factory mode to create bean?
IOCThere are two ways to create bean through factory mode:
1.Static factory method
2.Instance factory method
Static factory instantiation
1.Create an entity class first.
2.Create a static factory class, a static factory method.
3.Write the configuration file of Spring
4.Writing test classes
1 //Step 1: create an entity class 2 public class Car { 3 private int num; 4 private String brand; 5 public int getNum() { 6 return num; 7 } 8 public void setNum(int num) { 9 this.num = num; 10 } 11 public String getBrand() { 12 return brand; 13 } 14 public void setBrand(String brand) { 15 this.brand = brand; 16 } 17 public Car(int num, String brand) { 18 super(); 19 this.num = num; 20 this.brand = brand; 21 } 22 public Car() { 23 super(); 24 } 25 @Override 26 public String toString() { 27 return "Car [num=" + num + ", brand=" + brand + "]"; 28 } 29 }
//Step 2: create a static class public class StaticCarFactory { private static Map<Integer,Car> cars; //Static block of code static{ cars = new HashMap<Integer,Car>(); cars.put(1, new Car(1,"Audi ")); cars.put(2, new Car(2,"BMW ")); } //Static method public static Car getCar(int num){ return cars.get(id); } }
<?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"> <!-- Configuring static factory to create Car object--> <!-- factory-method:Point to static method getCar ()--> <bean id="car1" class="com.test.entity.StaticCarFactory" factory-method="getCar"> <!-- valueWhich key of the object to be generated--> <constructor-arg value="1"></constructor-arg> </bean> </beans>
//Step 4: test class public class Test { public static void main(String[] args) throws SQLException { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); Car car = (Car) applicationContext.getBean("car1"); System.out.println(car); } }
Instance factory method
1.Create instance factory class, factory method.
2.springConfigure bean in the configuration file.
3.Get the car2 object directly in the test class.
//Step 1: create instance factory class public class InstanceCarFactory { private Map<Integer,Car> cars; public InstanceCarFactory() { cars = new HashMap<Integer,Car>(); cars.put(1, new Car(1,"Audi ")); cars.put(2, new Car(2,"BMW ")); } public Car getCar(int num){ return cars.get(num); } }
<?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"> <!-- Configuring instance factory objects--> <bean id="carFactory" class="com.test.entity.InstanceCarFactory"></bean> <!-- Create a car object factory-bean from an instance factory object: place the ID of the instantiated factory object bean, and then set factory-method: invoke the method--> <bean id="car2" factory-bean="carFactory" factory-method="getCar"> <constructor-arg value="1"></constructor-arg> </bean> </beans>
The test class is the same as static engineering, and the result is the car object that generates key 1.
summary
The difference between the two methods is:
(1)To create a car object in a static factory method, you do not need to instantiate the factory object, because the static method of the static factory does not need to create an object to call. Therefore, spring configuration files only need to configure a Car bean instead of configuring factory bean.
(2)To create a car object using the instance factory method, you must instantiate the factory object first, because it is a non-static method that must be invoked through an object call and cannot be invoked directly through a class, so spring’s configuration file needs to first configure the factory bean, and then configure the Car bean.
IOCAutomatic loading
SpringThe framework provides a simpler way to load automatically without having to manually configure properties, and the IOC container automatically selects beans to complete dependency injection (DI) depending on the configuration of the beans.
Automatic loading can be done in two ways:
byName:Automatic loading by attribute name.
byType:Automatic loading of data types by attributes.
//First create an entity class, and generate setter/getter method and toString method. public class Person { private int id; private String name; private Car car; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Car getCar() { return car; } public void setCar(Car car) { this.car = car; } @Override public String toString() { return "Person [id=" + id + ", name=" + name + ", car=" + car + "]"; } }
<?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"> <!-- When creating person objects, no car attribute is configured in property.So the IOC container will automatically load.Autowire= "byName" means that the corresponding bean is loaded by matching the name of the attribute.The Person entity class has the car attribute, so the bean is injected into person.--> <bean id="p1" class="com.test.entity.Person" autowire="byName"> <property name="id" value="1"></property> <property name="name" value="ZhangSan"></property> </bean> <bean id="car1" class="com.test.entity.StaticCarFactory" factory-method="getCar"> <constructor-arg value="1"></constructor-arg> </bean> <!-- byTypeIt is configured by attribute data type.Keywords: autowire= "byType"--> <bean id="p2" class="com.test.entity.Person" autowire="byType"> <property name="id" value="1"></property> <property name="name" value="Zhang three "></property> </bean> <bean id="car2" class="com.test.entity.StaticCarFactory" factory-method="getCar"> <constructor-arg value="1"></constructor-arg> </bean> </beans>
Be careful:
(1)The byType is used for automatic loading. If two Car beans are configured in spring’s configuration file, but the IOC container does not know which beans should be loaded into the person object, it may report an error. So use byType to do automatic.When loading, the spring configuration file can only be configured with a Car bean to use byType.
(2)The priority of attribute injection is higher by manually using property tags. If automatic injection and manual configuration exist simultaneously, the configuration of property is the main method.
So in the daily code preparation process, try to avoid using byType to automatic assembly.