Two injection methods of Spring Bean

1. Set method injection:
.xml configuration file:

 <bean id="userDao" class="com.itlaobin.dao.impl.UserDaoImpl"></bean>
 <bean id="userService" class="com.itlaobin.service.impl.UserserviceImpl">
        <property name="userDao" ref="userDao"></property>
 </bean>

set method:

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

Presentation layer UserController

 ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
        Userservice userService = (Userservice) app.getBean("userService");
        userService.save();

Injection of the p namespace in the set:
(1) Add in the namespace

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

(2) Configuration file:

<bean id="userService" class="com.itlaobin.service.impl.UserserviceImpl" p:userDao-ref="userDao"  />

2. (with parameters) construction method injection:
the realization of the service construction method with parameters

 private  UserDao userDao;
    public UserserviceImpl(UserDao userDao) {
    
    
        this.userDao = userDao;
    }
    public UserserviceImpl() {
    
    
    }

Configuration file

 <bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl"></bean>
<bean id="userService" class="com.itheima.service.impl.UserserviceImpl">
        <constructor-arg name="userDao" ref="userDao"></constructor-arg>
</bean>

Guess you like

Origin blog.csdn.net/qq_44143902/article/details/109890840
Recommended