做java后台有一段时间了,其实涉及到的技术最多的还是spring、springmvc、maven、mybatis。今天主要说一下spring中的ioc。
spring主要的两个性质就是ioc(控制反转)以及aop(面向切面)
ioc其实可以这样理解,就是我需要一套房子,我属于一个类,这房子也属于一个类,我需要房子是一个套二的,简单装修的,有独卫,
有厕所的,然后房屋中介就给我找了一个类似的房子。所以不需要我自己去找这个房子。ioc就是起到房屋中介的作用。
简单代码:
一、定义一个接口
public interface service{
public void findHouse();
}
二、实现接口方法
public class serviceImpl{
public void findHouse(){
System.out.println("简单住房");
}
}
三、接下来是配置文件service.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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- id 表示组件的名字,class表示组件类 -->
<bean id="helloService" class="com.zzq.test.serviceImpl" />
</beans>
四、ioc调用(获取ioc容器)
public class test{
@Test
public void testService(){
ApplicationContext context=new ClassPathXmlApplicationContext(service.xml);
serviceImpl service=context.getBean("service",service.class);
service.findHouse();
}
}