Spring IOC新手入门
IOC(inversion of control)的中文解释是“控制反转”,对象的使用者不是创建者. 作用是将对象的创建 反转给spring框架来创建和管理。我们用到的对象都由Spring框架创建,使用对象时用对象的接口接受,能减少代码之间的耦合。
-
创建Maven工程, 添加坐标
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
-
准备好接口和实现类
StudentService.java
package cn.appmy;
public interface StudentService {
String getData();
}
StudentServiceImpl.java
package cn.appmy.impl;
import cn.appmy.StudentService;
public class StudentServiceImpl implements StudentService {
@Override
public String getData() {
return "菜菜";
}
}
-
创建spring的配置文件 (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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="cn.appmy.impl.StudentServiceImpl" id="studentService"></bean>
</beans>
-
创建工厂对象 获得bean 调用
import cn.appmy.StudentService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest {
@Test
public void Stest(){
ApplicationContext act=new ClassPathXmlApplicationContext("spring.xml");
StudentService studentService =(StudentService) act.getBean("studentService");
System.out.println(studentService.getData());
}
}