首先创建一个spring
在pom.xml中添加好依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
在java下新建一个ui包,创建两个接口
注意是Interface
一个为IAccountDaoImpl(模拟账户的持久层)
public interface IAccountDaoImpl {
void add();
}
另一个为IAccountServiceImpl(模拟账户的业务层)
public interface IAccountServiceImpl {
void add();
}
在java下新建一个dao包,用于实现上面那两个类
建立一个AccountService类(记得要继承IAccountServiceImpl):
public class AccountService implements IAccountServiceImpl{
private IAccountDaoImpl accountDao = new AccountDao();
public void add(){
accountDao.add();
}
}
建立一个AccountDao类(也要继承IAccountDaoImpl)
public class AccountDao implements IAccountDaoImpl {
public void add(){
System.out.println("accountDao begin");
}
}
创建一个表现层
//首先获取核心容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean");//此处的bean下文会提到
//其次获取bean对象
IAccountDaoImpl ad = (IAccountDaoImpl) ac.getBean("accountDao");
IAccountServiceImpl as = (IAccountServiceImpl)ac.getBean("accountService");
//最后输出获取的bean对象
System.out.println(ad);
System.out.println(as);
在main文件夹下面创建一个resources文件夹,并将其设置为Resources Root
新建一个xml,我起名为bean,可在spring的官网中一句关键字xmlns,搜到bean的配置代码
并输入bean的内容,以供表现层使用
<?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="accountService" class="dao.AccountService"></bean>
<bean id="accountDao" class="dao.AccountDao"></bean>
</beans>