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