Spring第三篇【依賴注入】
阿新 • • 發佈:2020-08-09
依賴注入(dependency injection):是Spring框架核心ioc(inversion of control)的具體實現
注入bean
通過set的方式
package com.example.demo.service.impl; import com.example.demo.dao.UserDao; import com.example.demo.service.UserService; public class UserServiceImpl implements UserService { private UserDao userDao; public void setUserDao(UserDao userDao) { this.userDao = userDao; } @Override public void save() { userDao.save(); } }
<?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="userDao" class="com.example.demo.dao.UserDao" /> <bean id="userServiceImpl" class="com.example.demo.service.impl.UserServiceImpl"> <property name="userDao" ref="userDao"/> </bean> </beans>
備註:
- name="userDao"中的userDao是根據setUserDao的UserDao(首字母變小寫)來的
通過p名稱空間的方式
p名稱空間注入的本質就是set注入
<?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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="userDao" class="com.example.demo.dao.UserDao" /> <bean id="userServiceImpl" class="com.example.demo.service.impl.UserServiceImpl" p:userDao-ref="userDao"/> </beans>
備註:
- userDao-ref中的userDao是根據setUserDao的UserDao(首字母變小寫)來的
通過構造器的方式
package com.example.demo.service.impl;
import com.example.demo.dao.UserDao;
import com.example.demo.service.UserService;
public class UserServiceImpl implements UserService {
private UserDao userDao;
public UserServiceImpl(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void save() {
userDao.save();
}
}
<?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="userDao" class="com.example.demo.dao.UserDao" />
<bean id="userServiceImpl" class="com.example.demo.service.impl.UserServiceImpl">
<constructor-arg name="userDao" ref="userDao"/>
</bean>
</beans>
備註:
- name="userDao"中的userDao是根據public UserServiceImpl(UserDao userDao)(構造器引數名)來的