控制反转(英语:Inversion of control,缩写为IoC),也叫做依赖注入(Dependency Injection,简称DI),是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度。
在面向对象开发过程中,类与类的关系可能非常复杂。而类与类之间的关系或依赖,导致系统的紧密耦合。
而依赖注入是解决对象间的紧密耦合,将原来在类内部控制的依赖交给系统去控制。
下面是基于注解的注入案例
配置文件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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:component-scan base-package="spring.test"/>
</beans>
主业务类PersonService.java
package spring.test;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
/**
* @function :
* @author :jy
* @company :万里网
* @date :2011-10-12
*/
@Service("person")
@Scope("prototype")
public class PersonService {
private InfoDao info;
private String username;
private int age;
@Resource(name="baseInfo") public void setInfo(InfoDao info){
this.info = info;
}
public PersonService(){
}
@PostConstruct
public void init(){
System.out.println("初始化完成");
}
@PreDestroy
public void destory(){
System.out.println("注销完成");
}
public PersonService(String username, int age){
this.username = username;
this.age = age;
}
@Override
public String toString() {
return "Person [username=" + username + ", age=" + age + "]";
}
public void printInfo(){
System.out.println(info);
}
}
数据访问组件InfoDao.java
package spring.test;
import org.springframework.stereotype.Repository;
/**
* @function :
* @author :jy
* @company :万里网
* @date :2011-10-12
*/
@Repository("baseInfo")
public class InfoDao {
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "User BaseInfo";
}
}
JUnit测试文件
package spring.test;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @function :
* @author :jy
* @company :万里网
* @date :2011-10-12
*/
public class TestSpring {
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test public void instanceBean(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
PersonService person = (PersonService) ctx.getBean("person");
person.printInfo();
}
}