控制反转 java_控制反转( Ioc)快速入门
2.1 什么是控制反轉(IOC:Inverse of Control)
IOC反轉控制,實際上就是將對象的創建權交給了Spring,程序員無需自己手動實例化對象。
可以看出來工廠的作用就是用來解耦合的,而在使用spring的過程中,spring就是充當這個工廠的角色。IOC反轉控制,實際上就是將對象的創建權交給了Spring,程序員無需自己手動實例化對象。
2.2、Spring編程—IOC程序實現
2.2.1建立spring工程(基于maven)
pom.xml
org.springframework
spring-context
4.2.6.RELEASE
junit
junit
4.12
2.2.2 編寫Java類
接口:public?interface?HelloService?{
public?void?sayHello();
}
實現類:public?class?HelloServiceImpl?implements?HelloService?{
public?void?sayHello(){
System.out.println("hello,spring");
}
}
2.2.3 編寫配置文件
在resource目錄下創建applicationContext.xml<?xml ?version="1.0"?encoding="UTF-8"?>
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">
id="helloService"
class="com.tianshouzhi.spring.HelloServiceImpl">
2.2.4 測試public?class?HelloServiceTest?{
//傳統寫法(緊密耦合)
@Test
public?void?traditionalTest(){
HelloService?service?=?new?HelloServiceImpl();
service.sayHello();
}
//使用Spring
@Test
public?void?springTest(){
//?工廠+反射+配置文件,實例化Service對象
ApplicationContext?context?=?new?ClassPathXmlApplicationContext(
"applicationContext.xml");
//通過工廠根據配置的實例名稱獲取實例對象
HelloService?service2=(HelloService)?context.getBean("helloService");
service2.sayHello();
}
}
總結
以上是生活随笔為你收集整理的控制反转 java_控制反转( Ioc)快速入门的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: sql intersect mysql_
- 下一篇: java工程转maven工程_将java