package com.yuank.service; public interface IAccountService { /** * 模擬保存帳戶 */ void saveAccount(); }
package com.yuank.service.impl; import com.yuank.dao.IAccountDao; import com.yuank.dao.impl.AccountDaoImpl; import com.yuank.service.IAccountService; /** * @author PC-Black * @version v1.0 * @date 2019/7/21 21:33 * @description TODO **/ public class AccountServiceImpl implements IAccountService { //手動初始化 private IAccountDao accountDao = new AccountDaoImpl(); public void saveAccount() { accountDao.saveAccount(); } }
package com.yuank.dao; public interface IAccountDao { void saveAccount(); }
package com.yuank.dao.impl; import com.yuank.dao.IAccountDao; /** * @author PC-Black * @version v1.0 * @date 2019/7/21 21:38 * @description TODO **/ public class AccountDaoImpl implements IAccountDao { public void saveAccount() { System.out.println("保存帳戶"); } }
import com.yuank.service.IAccountService; import com.yuank.service.impl.AccountServiceImpl; /** * @author PC-Black * @version v1.0 * @date 2019/7/21 21:39 * @description TODO **/ public class Client { public static void main(String[] args) { IAccountService accountService = new AccountServiceImpl(); accountService.saveAccount(); } }
<?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"> </beans>
<dependencies> <!--IOC相關依賴--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.6.RELEASE</version> </dependency> </dependencies>
<!-- 1. spring會經過反射的方式建立對象,並將該對象以key和value的方式存入到IOC容器中。 2. bean標籤的id就是key,value就是類的全路徑 3. 經過bean標籤將對象建立並存入到IOC容器的方式,咱們能夠稱之爲裝配bean 4. 只要能夠正常new出來的對象,均可以經過這種方式裝配到IOC容器中 --> <!--將service實現類裝配到IOC容器中--> <bean id="accountService" class="com.yuank.service.impl.AccountServiceImpl"/> <!-- 將dao實現類裝配到IOC容器中 --> <bean id="accountDao" class="com.yuank.dao.impl.AccountDaoImpl"/>
package com.yuank.web; import com.yuank.dao.IAccountDao; import com.yuank.service.IAccountService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author PC-Black * @version v1.0 * @date 2019/7/21 21:39 * @description TODO **/ public class Client { public static void main(String[] args) { // IAccountService accountService = new AccountServiceImpl(); //1. 加載配置文件 ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); //2. 從容器中獲取service IAccountService accountService = (IAccountService) ac.getBean("accountService"); //2.1 打印accountService對象 System.out.println(accountService); //3. 從容器中獲取dao IAccountDao accountDao = (IAccountDao) ac.getBean("accountDao"); //3.1 打印accountDao對象 System.out.println(accountDao); accountService.saveAccount(); } }
查看控制檯,咱們發現對象建立成功web