一个模块内的各个元素之间要高度紧密,但是各个模块之间的相互依存度却不要那么紧密。
#### 导入spring依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
#### 创建spring.xml配置文件
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>
<bean id="accountController" class="com.itheima.controller.AccountController">
<property name="accountService" ref="accountService"></property>
</bean>
</beans>
实体类
public class Account {
public Account(Integer id, String name, double money) {
this.id = id;
this.name = name;
this.money = money;
}
public Account() {
}
private Integer id;
private String name;
private double money;
}
控制器 com.ithiema.controller.AccountController.java
public class AccountController {
private AccountService accountService = new AccountServiceImpl();
public void save(Account account) {
accountService.save(account);
}
}
service接口 com.ithiema.service.AccountService.java
public interface AccountService {
void save(Account account);
}
serivce实现类 com.ithiema.service.impl.AccountServiceImpl.java
public class AccountServiceImpl implements AccountService {
@Override
public void save(Account account) {
System.out.println("保存用户信息成功:"+account);
}
}
测试类com.ithiema.controller.AccountControllerTest.java 需要引入junit依赖
测试类中,实例化一个ApplicationContext(ClassPathXmlApplicationContext)对象,,通过该类读取配置文件,并执行配置文件里配置的内容。
创建的对象就放在容器(ApplicationContext)里,需要使用的时候直接获取即可。
public class AccountControllerTest {
@Test
public void save() {
Account account = new Account(1, "特朗普", 5000000.0);
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
AccountController accountController = (AccountController) context.getBean("accountController");
accountController.save(account);
}
}