Spring file configuration of SSM / how spring performs dependency injection in pom file / what are the different dependency injection types and how to write them

Write before:
Then record your Spring learning journey. If you don't understand it, it is recommended to read a blog first Spring of SSM framework introduces the development process / IDEA how to build a spring project , detailed codes can be found in My Gitee warehouse SSM learning Clone download learn to use!

1.3 Spring configuration file

1.3.1 Bean label

1.3.1.1 purpose

Let the spring container call the configuration information to create an object

1.3.1.2 basic attributes

  • id: a unique identifier indicating that the Bean instance is unique in the Spring container and there is no duplicate
  • Class: the fully qualified name of the Bean. Use the Bean instance to configure the class to which the object to be created belongs. Generally, it is written to the class name

1.3.1.3 calling function

**Default call = = (class configured with class parameter in Bean) class = = parameterless constructor * *, class cannot run without parameterless constructor

1.3.1.4 Bean label Scope configuration

1.3.1.4.1 Scope parameters
parameterexplaininstantiation
singletonSingleton, that is, only one object is created in the current project, and each call is the same object. By defaultInstantiate when container is loaded
prototypeMultiple instances, you can call multiple times and each time is differentInstantiate when calling getBean
requestUsed for Web projects. After the Spring container creates the object, it stores it in the request field
sessionUsed for Web projects. After the Spring container creates the object, it stores it in the session domain
global sessionUsed in Portlet environment. If there is no Portlet, it is equivalent to session
1.3.1.4.2 Bean life cycle when using Scope
parameterobjects creatingObject runObject destruction
prototypeCreate when working with objectsObject usage isIf it is not used for a long time, it is recycled by the Java garbage collector
singletonCreated when the application load container is createdContainer in object inContainer destruction object destruction

That is, the object and container share the same life and death

1.3.1.5 Bean life cycle

  • Init method: Specifies the initialization method in the class
  • Destroy method: Specifies the destroy method in the class

1.3.1.6 Bean instantiation method

  • Parameterless construction method instantiation, the most commonly used, the focus
  • Factory static method instantiation
  • Factory instantiation method instantiation

The code in applicationContext is as follows:

  <!--Static factory-->  
  <bean id="UserDaoStaticFactory" class="com.demo.factory.StaticFactory" factory-method="getUserDao"></bean>
  
 <!-- Example factory-->  
   <bean id="factory" class="com.demo.factory.DynamicFactory"></bean>
  <bean id="UserDaoFactories" factory-bean="factory" factory-method="getUserDao"></bean>

1.3.2 dependency injection

1.3.2.1 problem introduction

At present, the external Web layer wants a Dao layer object, but the Web can only call the service object. How to implement it? The idea is to configure the container and let the Spring container generate a Dao layer object in the service interface implementation class again and pass it, that is, when the service object is called by getBean, the service object creates a Dao layer object in getBean.

1.3.2.2 dependency injection

The above method of creating objects through control inversion instead of direct creation is called dependency injection. It is a specific implementation of IOC and can reduce the coupling between business layers.

1.3.2.3 dependency injection mode

1.3.2.3.1 construction method
  • Use the construction method with parameters in ServiceImpl, and change it as follows:
 private UserDao userDao;  
  // Parametric structure
public UserServiceImpl(UserDao userDao) {  
    this.userDao = userDao;  
}  
public UserServiceImpl() {  
}
    public void sayHello() {  
// Soil method  
//        ApplicationContext appletContext = new ClassPathXmlApplicationContext("applicationContext.xml");  
//        UserDao userDao1 = (UserDao) appletContext.getBean("UserDao");  
//        userDao1.sayHello();  
  
// Dependency injection  
 userDao.sayHello();  
 }
  • Configure in applicationContext as follows:
<bean id="UserDao" class="com.demo.dao.impl.UserDaoImpl"></bean> 
    <!--Injection by construction method-->  
 <bean id="UserService" class="com.demo.service.impl.UserServiceImpl">  
<!--        name Is the parameter name in the constructor, ref For reference-->  
 		<constructor-arg name="userDao" ref="UserDao"/>  
 </bean>
1.3.2.3.1 set method
  • Add the set method of dao in ServiceImpl and change it as follows:
  // Injection with set method
 public void setUserDao(UserDao userDao) {  
        this.userDao = userDao;  
 }  
  • Configure in applicationContext as follows:
<!--Dependency injection-->  
<bean id="UserDao" class="com.demo.dao.impl.UserDaoImpl"></bean>  
  
<bean id="UserService" class="com.demo.service.impl.UserServiceImpl" >  
 <!-- name by setUserDao in set Second half userDao  
 ref The parameters are configured for the above injection bean of id-->  
 		<property name="userDao" ref="UserDao"></property>
 </bean>

1.3.2.4 dependency injection data type

1.3.2.4.1 object type

The above operations have been explained and will not be repeated!

1.3.2.4.2 common, reference and set data types
  • Create int, String, List, map and Properties in the entity class and inject them with the set method, as follows:
/ Common data type  
 int age;  
// Reference data type  
 String username;  
// aggregate  
 private List<String> userList;  
 private Map<String, User> userMap;  
//    property  
 private Properties properties;  
  
// Injection with set method  
  
 public List<String> getUserList() {  
        return userList;  
 }  
  
    public void setUserList(List<String> userList) {  
        this.userList = userList;  
 }  
  
    public Map<String, User> getUserMap() {  
        return userMap;  
 }  
  
    public void setUserMap(Map<String, User> userMap) {  
        this.userMap = userMap;  
 }  
  
    public Properties getProperties() {  
        return properties;  
 }  
  
    public void setProperties(Properties properties) {  
        this.properties = properties;  
 }  
  
    public void setAge(int age) {  
        this.age = age;  
 }  
  
    public void setUsername(String username) {  
        this.username = username;  
 }  
  
    public void show() {  
        System.out.println("Test common data types");  
 		System.out.println("username = " + username + ",   age = " + age);  
 		System.out.println("Collection data type");  
 		System.out.println(userList);  
 		System.out.println(userMap);  
 		System.out.println(properties);  
 }
  • Configure in applicationContext as follows:
<!-- Dependency injection other data types,Not used when injecting other data types ref,only need value assignment-->  
<bean id="IOCData" class="com.demo.dao.impl.IOCData">  
<!-- Common data type -->  
			<property name="username" value="Wang Zuxian"></property>  
			<property name="age" value="20"></property>  
<!-- Injection set data type-->  
			<property name="userList">  
				<list>
   				<value>Lin Qingxia</value>  
					<value>Liu Shishi</value>  
				</list>
   		</property>
   	<property name="userMap">  
			<map> 
   			<entry key="Cartoon 1" value-ref="user1" />  
				<entry key="Cartoon 2" value-ref="user2" />  
				<entry key="Cartoon 3" value-ref="user3" />  
			</map> 
   			</property>
   			<property name="properties">  
					<props >
   					<prop key="Guan Yu">Zhan qinqiong</prop>  
						<prop key="Zhang San">Outlaw maniac</prop>  
					</props> 

   			</property>
</bean>

1.3.2.5 testing

Unit test with Junit, the same as
Spring of SSM framework introduces the development process / IDEA how to build a spring project The corresponding results will appear on the console for the project test operation in! For example, the test results of injecting other data types are shown in the figure below

1.3.3 sub module development

1.3.3.1 problem description

The actual development process will be very complex. It is impossible to configure all files into the Spring configuration xml file. Each person will be responsible for writing one piece into his own configuration file, and then import and load it in the main configuration file through the import tag, which is also convenient for later maintenance!

1.3.3.2 introduction code

<import resource="applicationContext-xxx.xml"></import>

Tags: Java Programming Spring Back-end

Posted on Thu, 11 Nov 2021 18:01:03 -0500 by ProTec