Srping--Ioc
?Ioc控制反转模式和DI依赖注人起着举足轻重的作用。?????Ioc说白了,就是容器控制程序之间的关系。而非传统的程序代码直接控制。所谓控制反转就是控制权有应用代码中转移到外部容器中,控制权的转移,即所谓的反转。??????所谓依赖注入就是组件之间的关系有容器运行期决定,换句话说就是由容器动态的讲某种关系注人到组件之间。??????原理是很简单的,关键是怎么去实践,下面做了个列子,是将Ioc和DI在Spring中实现.....?????在做之间,先说明一下,我用的IDE是Eclipse,这个列子不是一个WEB应用,而是一个JAVA项目....????(1) package spring;??????????public interface Action {
??????????public String execute(String message);
??????????}????(2)package spring;?????????public class LowerAction implements Action {
?????????private String str;
?
?????????public String getStr() {
?????????return str;
?????????}??????????public void setStr(String str) {
??????????this.str = str;
??????????}??????????public String execute(String message) {
??
???????????return (getStr()+","+message).toLowerCase();
????????????}???????????}?????(3)package spring;?????????public class UpperAction implements Action {?????????String str;
?
????????????public String getStr() {
?????????????return str;
?????????????}?????????????public void setStr(String str) {
?????????????this.str = str;
?????????????}????????????public String execute(String message) {
??
????????????return (getStr()+","+message).toUpperCase();
?
??????????????}?
????????????}
(4)package spring;import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.io.Resource;import common.Logger;public class Test {?public static void main(String[] args) {
??Logger log = Logger.getLogger(Test.class);
??
??ApplicationContext ctx = new FileSystemXmlApplicationContext("bean.xml");
??Action action = (Action) ctx.getBean("TheAction");
??System.out.println(action.execute("liaolu"));
??log.debug(action.execute("liaolu"));}?(5)Spring 的配置文件bean.xml:<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"><beans>
?<description>快速开发</description>
?<bean id="TheAction" class="spring.UpperAction">//只是注人UpperAction类
??<property name="str">
???<value>HELLO</value>
??</property>
?</bean>
</beans>??????大家可以看到,这个列子所用的是设值注入。这也是Spring中大量运用的一种注入方式。然而其他的2种方式既接口注人和构造子注入,构造子注人也经常使用。
?