69-IOC解决耦合问题

37 阅读1分钟
一个模块内的各个元素之间要高度紧密,但是各个模块之间的相互依存度却不要那么紧密。
#### 导入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">
    <!--创建service对象-->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>
    <!--创建controller对象-->
    <bean id="accountController" class="com.itheima.controller.AccountController">
        <!--通过set方法给AccountService属性赋值-->
        <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; 
		//此处省略set和get方法
}
控制器 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依赖
测试类中,实例化一个ApplicationContextClassPathXmlApplicationContext)对象,,通过该类读取配置文件,并执行配置文件里配置的内容。 
创建的对象就放在容器(ApplicationContext)里,需要使用的时候直接获取即可。    
 public class AccountControllerTest {

    @Test
    public void save() {
        //创建Account对象
        Account account = new Account(1, "特朗普", 5000000.0);
        //创建IOC容器
        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        //从容器中获取AccountController对象
        AccountController  accountController = (AccountController) context.getBean("accountController");
        //调用save方法
        accountController.save(account);
    }
}