concept
-
Dependency injection (DI).
-
Dependency: the creation of Bean objects depends on the container Dependent resources of Bean objects
-
Injection: refers to the resources that the Bean object depends on, which are set and assembled by the container
Constructor Injection
We have already talked about the case before
Set injection (key)
The injected attribute must have a set method. The method name of the set method is capitalized by the initial letter of set + attribute. If the attribute is of boolean type and there is no set method, it is
Test pojo class:
Address.java
public class Address { private String address; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } } Student.java package com.kuang.pojo; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; public class Student { private String name; private Address address; private String[] books; private List<String> hobbys; private Map<String,String> card; private Set<String> games; private String wife; private Properties info; public void setName(String name) { this.name = name; } public void setAddress(Address address) { this.address = address; } public void setBooks(String[] books) { this.books = books; } public void setHobbys(List<String> hobbys) { this.hobbys = hobbys; } public void setCard(Map<String, String> card) { this.card = card; } public void setGames(Set<String> games) { this.games = games; } public void setWife(String wife) { this.wife = wife; } public void setInfo(Properties info) { this.info = info; } public void show(){ System.out.println("name="+ name + ",address="+ address.getAddress() + ",books=" ); for (String book:books){ System.out.print("<<"+book+">>\t"); } System.out.println("\n hobby:"+hobbys); System.out.println("card:"+card); System.out.println("games:"+games); System.out.println("wife:"+wife); System.out.println("info:"+info); } }
1. Constant injection
<bean id="student" class="com.kuang.pojo.Student">
<property name="name" value="Xiao Ming"/>
</bean>
Test:
@Test public void test01(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Student student = (Student) context.getBean("student"); System.out.println(student.getName()); }
2. Bean injection
Note: the value here is a reference, ref
<bean id="addr" class="com.kuang.pojo.Address"> <property name="address" value="Chongqing"/> </bean> <bean id="student" class="com.kuang.pojo.Student"> <property name="name" value="Xiao Ming"/> <property name="address" ref="addr"/> </bean>
3. Array injection
<bean id="student" class="com.kuang.pojo.Student">
<property name="name" value="Xiao Ming"/>
<property name="address" ref="addr"/>
<property name="books">
<array>
<value>Journey to the West</value>
<value>The Dream of Red Mansion</value>
<value>Water Margin</value>
</array>
</property>
</bean>
4. List injection
<property name="hobbys"> <list> <value>listen to the music</value> <value>watch movie</value> <value>Mountain climbing</value> </list> </property>
5. Map injection
<property name="card"> <map> <entry key="China Post" value="456456456465456"/> <entry key="build" value="1456682255511"/> </map> </property>
6. set injection
<property name="games"> <set> <value>LOL</value> <value>BOB</value> <value>COC</value> </set> </property>
7. Null injection
<property name="wife"><null/></property>
8. Properties injection
<property name="info"> <props> <prop key="Student number">20190604</prop> <prop key="Gender">male</prop> <prop key="full name">Xiao Ming</prop> </props> </property>
p named and c named injection
User.java: [Note: there is no parameter constructor here!]
public class User { private String name; private int age; public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
1. P namespace injection: the constraint file needs to be added to the header file
Import constraints : xmlns:p="http://www.springframework.org/schema/p"
<!--P(attribute: properties)Namespace , Property should still be set set method-->
<bean id="user" class="com.kuang.pojo.User" p:name="Mad God" p:age="18"/>
2. c namespace injection: you need to add constraint files in the header file
Import constraints : xmlns:c="http://www.springframework.org/schema/c"
<!--C(structure: Constructor)Namespace , Property should still be set set method-->
<bean id="user" class="com.kuang.pojo.User" c:name="Mad God" c:age="18"/>
Found the problem: it's red. We didn't write a reference structure just now!
Solution: add the constructor with parameters. Here you can also know that c is the so-called constructor injection!
Test code:
@Test public void test02(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); User user = (User) context.getBean("user"); System.out.println(user); }
Scope of Bean
In Spring, the subjects that make up the application and the objects managed by the Spring IoC container are called beans. Simply put, bean is an object initialized, assembled and managed by IoC container
Among the several scopes, the request and session scopes are only used in web-based applications (don't care what web application framework you use), and can only be used in Web-based Spring ApplicationContext environment.
Singleton
When the scope of a bean is singleton, there will only be one shared bean instance in the Spring IoC container, and all requests for a bean will only return the same instance of the bean as long as the id matches the bean definition. Singleton is a singleton type, which automatically creates a bean object when creating a container. It exists whether you use it or not, and the object obtained each time is the same object. Note that the singleton scope is the default scope in Spring. To define a bean as a singleton in XML, you can configure it as follows:
<bean id="ServiceImpl" class="cn.csdn.service.ServiceImpl" scope="singleton">
Test:
@Test public void test03(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); User user = (User) context.getBean("user"); User user2 = (User) context.getBean("user"); System.out.println(user==user2); }
Prototype
When the scope of a bean is prototype, it means that a bean definition corresponds to multiple object instances. A prototype scoped bean will cause a new bean instance to be created every time a request is made to the bean (inject it into another bean, or call the container's getBean() method programmatically). Prototype is a prototype type. It is not instantiated when we create the container. Instead, we create an object when we get the bean, and the object we get each time is not the same object. As a rule of thumb, you should use the prototype scope for stateful beans and the singleton scope for stateless beans. Define a bean as a prototype in XML, which can be configured as follows:
<bean id="account" class="com.foo.DefaultAccount" scope="prototype"/>
Or
<bean id="account" class="com.foo.DefaultAccount" singleton="false"/>
Request
When the scope of a bean is Request, it means that in an HTTP Request, a bean definition corresponds to an instance; That is, each HTTP Request will have its own bean instance, which is created according to a bean definition. The scope of ApplicationContext is valid only in the case of spring. Consider the following bean definitions:
<bean id="loginAction" class=cn.csdn.LoginAction" scope="request"/>
For each HTTP request, the Spring container will create a new loginaction bean instance according to the loginaction bean definition, and the loginaction bean instance is only valid in the current HTTP request. Therefore, you can safely change the internal state of the created instance according to the needs, while for the instances created according to the loginaction bean definition in other requests, You will not see these state changes specific to a request. When the processing of the request ends, the bean instance of the request scope will be destroyed.
Session
When the scope of a bean is Session, it means that in an HTTP Session, a bean definition corresponds to an instance. The scope of ApplicationContext is valid only in the case of spring. Consider the following bean definitions:
<bean id="userPreferences" class="com.foo.UserPreferences" scope="session"/>
For an HTTP Session, the Spring container will create a new userPreferences bean instance according to the userPreferences bean definition, and the userPreferences bean is only valid in the current HTTP Session. Like the request scope, you can safely change the internal state of the created instance as needed. However, for instances created according to userPreferences in other HTTP sessions, you will not see these state changes specific to an HTTP Session. When the HTTP Session is finally discarded, the beans within the scope of the HTTP Session will also be discarded.