• This is the first day of my participation in the Gwen Challenge in November. Check out the details: the last Gwen Challenge in 2021

1. Dependency injection introduction to beans

  1. Create a UserService that internally calls the UserDao’s save() method

UserService

public interface UserService {
    public void save(a);
}
Copy the code
  • The last time you invoked the userDao by creating a test class, the userDao is generated by Spring

  • This time userService is used to invoke the userDao

UserServiceImpl

public class UserServiceImpl implements UserService {
    @Override
    public void save(a) {
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserDao userDao = (UserDao) app.getBean("userDao"); userDao.save(); }}Copy the code
  • Create a test class UserController to call the methods of the userDao implementation class in userService

  1. Give the creation of UserServiceImpl to Spring
<bean id="userDao" class="com.xdr630.dao.impl.UserDaoImpl"></bean>
<bean id="userService" class="com.xdr630.service.Impl.UserServiceImpl"></bean>
Copy the code
  1. Get the UserService from the Spring container to operate
public class UserController {
    public static void main(String[] args) {
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) app.getBean("userService"); userService.save(); }}Copy the code

2. Dependency injection analysis of beans

  • Currently, both UserService and UserDao instances exist in the Spring container. The current practice is to obtain the UserService and UserDao instances outside the container and combine them in the application.

  • Because both UserService and UserDao are in the Spring container, and the final application uses UserService directly, you can set the UserDao inside the UserService in the Spring container.

3. Dependency injection concept of beans

  • Dependency Injection: It is a concrete implementation of IOC, the core of the Spring framework.

  • When you write your program, you leave the creation of the object to Spring through inversion of control, but you can’t have code that doesn’t have dependencies.

  • IOC decoupling only reduces their dependencies, but does not eliminate them. For example, the business layer still calls the methods of the persistence layer.

  • The dependency between the business layer and the persistence layer will be maintained by Spring after Spring is used.

In simple terms, we simply sit back and wait for the framework to pass persistence layer objects into the business layer without having to fetch them ourselves.

4. Dependency injection of beans

How to inject the UserDao into the UserService?

  1. A constructor
  2. Set method

Add the setUserDao method to UserServiceImpl

public class UserServiceImpl implements UserService {

    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void save(a) { userDao.save(); }}Copy the code

Configure the Spring container to call the set method for injection

<bean id="userDao" class="com.xdr630.dao.impl.UserDaoImpl"></bean>

<bean id="userService" class="com.xdr630.service.Impl.UserServiceImpl">
        <property name="userDao" ref="userDao"></property>
 </bean>
Copy the code
  • The name in the property refers to the setXXX property name, which changes the UserDao to a lower-case UserDao

  • Ref refers to the object to be referenced, in this case directly to the id=userDao in the previous bean
  • Inject the userDao from the container into the userDao method in the userService

1) Set method injection

P namespace injection is also set injection, but it is more convenient than the above set injection, which is mainly reflected in the configuration file as follows:

First, we need to introduce the P namespace:

xmlns:p="http://www.springframework.org/schema/p"
Copy the code

Second, you need to modify the injection method

<bean id="userService" class="com.xdr630.service.Impl.UserServiceImpl" p:userDao-ref="userDao"/>
Copy the code
  • test

Constructor injection creates a parameterized construct

public class UserServiceImpl implements UserService {

    private UserDao userDao;

    public UserServiceImpl(a) {}public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void save(a) { userDao.save(); }}Copy the code
<bean id="userDao" class="com.xdr630.dao.impl.UserDaoImpl"></bean>

<bean id="userService" class="com.xdr630.service.Impl.UserServiceImpl">
        <constructor-arg name="userDao" ref="userDao"></constructor-arg>
</bean>
Copy the code
  • test

5. The dependency injection data type of the Bean

  • The above operations are all injected reference beans, except that references to objects can be injected. Common data types, collections, and so on can be injected into containers.

  • Three data types for injecting data

Common data types refer to data types collection data types

  • The set method injection is used as an example to demonstrate the injection of common data types and collection data types.

5.1 Injecting Common Data Types

public class UserDaoImpl implements UserDao {

    private String username;
    private int age;

    public void setUsername(String username) {
        this.username = username;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public void save(a) {
        System.out.println("username=" + username + "\n" + "age=" + age);
        System.out.println("save running......"); }}Copy the code
<bean id="userDao" class="com.xdr630.dao.impl.UserDaoImpl">
        <property name="username" value="xdr"/>
        <property name="age" value="22"/>
</bean>
Copy the code

5.2 Set Data Types (List <String>The injection

public interface UserDao {
    public void save(a);
}
Copy the code
public class UserDaoImpl implements UserDao {

    private List<String> strList;
	
	public void setStrList(List<String> strList) {
        this.strList = strList;
    }
	
	public void save(a) {
		System.out.println(strList);
		System.out.println("save running......");
    }
Copy the code
public interface UserService {
    public void save(a);
}

Copy the code
public class UserServiceImpl implements UserService {

    private UserDao userDao;


    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public UserServiceImpl(a) {}public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void save(a) { userDao.save(); }}Copy the code
  • List<String>Is a common data type, use value, or ref if it’s User or some other object
<bean id="userDao" class="com.xdr630.dao.impl.UserDaoImpl">
        <property name="strList">
            <list>
                <value>aaa</value>
                <value>bbb</value>
                <value>ccc</value>
            </list>
        </property>
</bean>

<bean id="userService" class="com.xdr630.service.Impl.UserServiceImpl">
        <constructor-arg name="userDao" ref="userDao"></constructor-arg>
</bean>
Copy the code
public class UserController {
    public static void main(String[] args) {
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) app.getBean("userService"); userService.save(); }}Copy the code

5.3 Collection Data Types (Map<String User>The injection

  • Create a User class
public class User {
    private String name;
    private String addr;

    public String getName(a) {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddr(a) {
        return addr;
    }

    public void setAddr(String addr) {
        this.addr = addr;
    }

    @Override
    public String toString(a) {
        return "User{" +
                "name='" + name + '\' ' +
                ", addr='" + addr + '\' ' +
                '} '; }}Copy the code
  • Set method injection
public class UserDaoImpl implements UserDao {   
	private List<User> userList; 
	
	public void setUserList(List<User> userList) {
		this.userList = userList;    
	}    
		
	public void save(a) { 
		System.out.println(userList);     
		System.out.println("save running......"); }}Copy the code
  • Value-ref indicates a value reference. The referenced object must exist in the container before it can be injected. So create user1 and user2 later and reference the corresponding values
<bean id="userDao" class="com.xdr630.dao.impl.UserDaoImpl">
        <property name="userMap">
            <map>
                <entry key="u1" value-ref="user1"></entry>
                <entry key="u2" value-ref="user2"></entry>
            </map>
        </property>
</bean>

<bean id="user1" class="com.xdr630.domain.User">
	<property name="name" value="tom"/>
	<property name="addr" value="beijing"/>
</bean>

<bean id="user2" class="com.xdr630.domain.User">
	<property name="name" value="jerry"/>
	<property name="addr" value="shanghai"/>
</bean>

<bean id="userService" class="com.xdr630.service.Impl.UserServiceImpl">
        <constructor-arg name="userDao" ref="userDao"></constructor-arg>
</bean>
Copy the code
public class UserController {
    public static void main(String[] args) {
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) app.getBean("userService"); userService.save(); }}Copy the code

5.4 Injection of collection data types

  • Properties itself is a string
<bean id="userDao" class="com.xdr630.dao.impl.UserDaoImpl">
	<property name="properties">
		<props>
			<prop key="p1">ppp1</prop>
			<prop key="p2">ppp2</prop>
			<prop key="p3">ppp3</prop>
		</props>
	</property>
</bean>

<bean id="userService" class="com.xdr630.service.Impl.UserServiceImpl">
        <constructor-arg name="userDao" ref="userDao"></constructor-arg>
</bean>
Copy the code
public class UserDaoImpl implements UserDao {   
	private Properties properties;
	
	public void setProperties(Properties properties) {
        this.properties = properties;
    } 
		
	public void save(a) { 
		System.out.println(properties);     
		System.out.println("save running......"); }}Copy the code
public class UserController {
    public static void main(String[] args) {
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) app.getBean("userService"); userService.save(); }}Copy the code

  • Put the above configured injection objects together and run:

6. Introduce other configuration files (module development)

  • In practice, Spring has a lot of configuration, which makes it cumbersome and bulky, so some of the configuration can be disassembled into other configuration files and loaded in the main Spring configuration file via the import tag

  • For example, you can reference the configuration files of other modules in the master configuration file

  • By quoting:
<import resource="applicationContext-xxx.xml"/>
Copy the code
  • After the reference, once the master configuration file is loaded, the sub-files are loaded together

7. Key configuration of Spring

<bean> tag ID attribute: Unique identification of the bean instance in the container. It is not allowed to be duplicatedclassProperty: to be instantiatedBeanFully qualified name of thescopeProperties:BeanThe scope of action ofSingleton(Default) andprototype
    <property> Tags: property injectionnameAttribute: The name of the attributevalueProperty: Injected normal property valuerefProperty: Injected object reference value <list< > tagmap< > tagproperties< > tagconstructor-arg< > tagimport> Tags: import othersSpringThe points of the fileCopy the code