最近,买了本Spring入门书:spring In Action 。大致浏览了下感觉还不错。就是入门了点。Manning的书还是不错的,我虽然不像哪些只看Manning书的人那样专注于Manning,但怀着崇敬的心情和激情通览了一遍。又一次接受了IOC 、DI、AOP等Spring核心概念。 先就IOC和DI谈一点我的看法。
IoC与DI
首先想说说IoC(Inversion of Control,控制倒转)。这是spring的核心,贯穿始终。所谓IoC,对于spring框架来说,就是由spring来负责控制对象的生命周期和对象间的关系。这是什么意思呢,举个简单的例子,我们是如何找女朋友的?常见的情况是,我们到处去看哪里有长得漂亮身材又好的mm,然后打听她们的兴趣爱好、qq号、电话号、ip号、iq号………,想办法认识她们,投其所好送其所要,然后嘿嘿……这个过程是复杂深奥的,我们必须自己设计和面对每个环节。传统的程序开发也是如此,在一个对象中,如果要使用另外的对象,就必须得到它(自己new一个,或者从JNDI中查询一个),使用完之后还要将对象销毁(比如Connection等),对象始终会和其他的接口或类藕合起来。
那么IoC是如何做的呢?有点像通过婚介找女朋友,在我和女朋友之间引入了一个第三者:婚姻介绍所。婚介管理了很多男男女女的资料,我可以向婚介提出一个列表,告诉它我想找个什么样的女朋友,比如长得像李嘉欣,身材像林熙雷,唱歌像周杰伦,速度像卡洛斯,技术像齐达内之类的,然后婚介就会按照我们的要求,提供一个mm,我们只需要去和她谈恋爱、结婚就行了。简单明了,如果婚介给我们的人选不符合要求,我们就会抛出异常。整个过程不再由我自己控制,而是有婚介这样一个类似容器的机构来控制。Spring所倡导的开发方式就是如此,所有的类都会在spring容器中登记,告诉spring你是个什么东西,你需要什么东西,然后spring会在系统运行到适当的时候,把你要的东西主动给你,同时也把你交给其他需要你的东西。所有的类的创建、销毁都由 spring来控制,也就是说控制对象生存周期的不再是引用它的对象,而是spring。对于某个具体的对象而言,以前是它控制其他对象,现在是所有对象都被spring控制,所以这叫控制反转。如果你还不明白的话,我决定放弃。
1.3之后一个重要特征是反射(reflection),它允许程序在运行的时候动态的生成对象、执行对象的方法、改变对象的属性,spring就是通过反射来实现注入的。关于反射的相关资料请查阅java doc。
下面来让大家了解一下Spring到底是怎么运行的。
- public static void main(String[] args) {
- ApplicationContext context = new FileSystemXmlApplicationContext(
- "applicationContext.xml");
- Animal animal = (Animal) context.getBean("animal");
- animal.say();
- }
- public static void main(String[] args) {
- ApplicationContext context = new FileSystemXmlApplicationContext(
- "applicationContext.xml");
- Animal animal = (Animal) context.getBean("animal");
- animal.say();
- }
- <bean id="animal" class="phz.springframework.test.Cat">
- <property name="name" value="kitty" />
- </bean>
- <bean id="animal" class="phz.springframework.test.Cat">
- <property name="name" value="kitty" />
- </bean>
- public class Cat implements Animal {
- private String name;
- public void say() {
- System.out.println("I am " + name + "!");
- }
- public void setName(String name) {
- this.name = name;
- }
- }
- public class Cat implements Animal {
- private String name;
- public void say() {
- System.out.println("I am " + name + "!");
- }
- public void setName(String name) {
- this.name = name;
- }
- }
- public interface Animal {
- public void say();
- }
- /* Bean Id */
- private String id;
- /* Bean Class */
- private String type;
- /* Bean Property */
- private Map<String, Object> properties = new HashMap<String, Object>();
- /* Bean Id */
- private String id;
- /* Bean Class */
- private String type;
- /* Bean Property */
- private Map<String, Object> properties = new HashMap<String, Object>();
- <bean id="test" class="Test">
- <property name="testMap">
- <map>
- <entry key="a">
- <value>1</value>
- </entry>
- <entry key="b">
- <value>2</value>
- </entry>
- </map>
- </property>
- </bean>
- <bean id="test" class="Test">
- <property name="testMap">
- <map>
- <entry key="a">
- <value>1</value>
- </entry>
- <entry key="b">
- <value>2</value>
- </entry>
- </map>
- </property>
- </bean>
- if (beanProperty.element("map") != null) {
- Map<String, Object> propertiesMap = new HashMap<String, Object>();
- Element propertiesListMap = (Element) beanProperty
- .elements().get(0);
- Iterator<?> propertiesIterator = propertiesListMap
- .elements().iterator();
- while (propertiesIterator.hasNext()) {
- Element vet = (Element) propertiesIterator.next();
- if (vet.getName().equals("entry")) {
- String key = vet.attributeValue("key");
- Iterator<?> valuesIterator = vet.elements()
- .iterator();
- while (valuesIterator.hasNext()) {
- Element value = (Element) valuesIterator.next();
- if (value.getName().equals("value")) {
- propertiesMap.put(key, value.getText());
- }
- if (value.getName().equals("ref")) {
- propertiesMap.put(key, new String[] { value
- .attributeValue("bean") });
- }
- }
- }
- }
- bean.getProperties().put(name, propertiesMap);
- }
- if (beanProperty.element("map") != null) {
- Map<String, Object> propertiesMap = new HashMap<String, Object>();
- Element propertiesListMap = (Element) beanProperty
- .elements().get(0);
- Iterator<?> propertiesIterator = propertiesListMap
- .elements().iterator();
- while (propertiesIterator.hasNext()) {
- Element vet = (Element) propertiesIterator.next();
- if (vet.getName().equals("entry")) {
- String key = vet.attributeValue("key");
- Iterator<?> valuesIterator = vet.elements()
- .iterator();
- while (valuesIterator.hasNext()) {
- Element value = (Element) valuesIterator.next();
- if (value.getName().equals("value")) {
- propertiesMap.put(key, value.getText());
- }
- if (value.getName().equals("ref")) {
- propertiesMap.put(key, new String[] { value
- .attributeValue("bean") });
- }
- }
- }
- }
- bean.getProperties().put(name, propertiesMap);
- }
- public static Object newInstance(String className) {
- Class<?> cls = null;
- Object obj = null;
- try {
- cls = Class.forName(className);
- obj = cls.newInstance();
- } catch (ClassNotFoundException e) {
- throw new RuntimeException(e);
- } catch (InstantiationException e) {
- throw new RuntimeException(e);
- } catch (IllegalAccessException e) {
- throw new RuntimeException(e);
- }
- return obj;
- }
- public static Object newInstance(String className) {
- Class<?> cls = null;
- Object obj = null;
- try {
- cls = Class.forName(className);
- obj = cls.newInstance();
- } catch (ClassNotFoundException e) {
- throw new RuntimeException(e);
- } catch (InstantiationException e) {
- throw new RuntimeException(e);
- } catch (IllegalAccessException e) {
- throw new RuntimeException(e);
- }
- return obj;
- }
- public static void setProperty(Object obj, String name, String value) {
- Class<? extends Object> clazz = obj.getClass();
- try {
- String methodName = returnSetMthodName(name);
- Method[] ms = clazz.getMethods();
- for (Method m : ms) {
- if (m.getName().equals(methodName)) {
- if (m.getParameterTypes().length == 1) {
- Class<?> clazzParameterType = m.getParameterTypes()[0];
- setFieldValue(clazzParameterType.getName(), value, m,
- obj);
- break;
- }
- }
- }
- } catch (SecurityException e) {
- throw new RuntimeException(e);
- } catch (IllegalArgumentException e) {
- throw new RuntimeException(e);
- } catch (IllegalAccessException e) {
- throw new RuntimeException(e);
- } catch (InvocationTargetException e) {
- throw new RuntimeException(e);
- }
- }
- public static void setProperty(Object obj, String name, String value) {
- Class<? extends Object> clazz = obj.getClass();
- try {
- String methodName = returnSetMthodName(name);
- Method[] ms = clazz.getMethods();
- for (Method m : ms) {
- if (m.getName().equals(methodName)) {
- if (m.getParameterTypes().length == 1) {
- Class<?> clazzParameterType = m.getParameterTypes()[0];
- setFieldValue(clazzParameterType.getName(), value, m,
- obj);
- break;
- }
- }
- }
- } catch (SecurityException e) {
- throw new RuntimeException(e);
- } catch (IllegalArgumentException e) {
- throw new RuntimeException(e);
- } catch (IllegalAccessException e) {
- throw new RuntimeException(e);
- } catch (InvocationTargetException e) {
- throw new RuntimeException(e);
- }
- }