特别說明: spring5版本是用jdk8編寫的,是以要求我們的jdk版本是8及以上。 同時tomcat的版本要求8.5及以上。
一、導入maven依賴
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
</dependencies>
二、建立相應的接口和實作類
檔案目錄如下,後面給出相應的代碼
- AccountDaoImpl
package com.dgut.dao.impl;
import com.dgut.dao.IAccountDao;
/**
* 賬戶的持久層實作類
*/
public class AccountDaoImpl implements IAccountDao {
public void saveAccount(){
System.out.println("儲存了賬戶");
}
}
- IAccountDao
package com.dgut.dao;
/**
* 賬戶的持久層接口
*/
public interface IAccountDao {
/**
* 模拟儲存賬戶
*/
void saveAccount();
}
- IAccountServiceImpl
package com.dgut.service.impl;
import com.dgut.dao.IAccountDao;
import com.dgut.dao.impl.AccountDaoImpl;
import com.dgut.service.IAccountService;
/**
* 賬戶的業務層實作類
*/
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao = new AccountDaoImpl();
public void saveAccount(){
accountDao.saveAccount();
}
}
- IAccountService
package com.dgut.service;
/**
* 賬戶業務層的接口
*/
public interface IAccountService {
/**
* 模拟儲存賬戶
*/
void saveAccount();
}
- Client
package com.dgut.ui;
import com.dgut.dao.IAccountDao;
import com.dgut.service.IAccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* 模拟一個表現層,用于調用業務層
*/
public class Client {
/**
* 擷取ioc核心容器,并根據id擷取對象
* @param args
*/
public static void main(String[] args) {
//1.擷取核心容器對象
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根據id擷取bean對象
IAccountService accountService = (IAccountService)ac.getBean("accountService");
IAccountDao accountDao = ac.getBean("accountDao", IAccountDao.class);
System.out.println(accountDao);
System.out.println(accountService);
}
}
- beam.xml
<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">
<!--把對象的建立交給spring來管理-->
<bean id="accountService" class="com.dgut.service.impl.AccountServiceImpl"></bean>
<bean id="accountDao" class="com.dgut.dao.impl.AccountDaoImpl"></bean>
</beans>
三、測試
在Client中運作main方法進行測試