本文共 4753 字,大约阅读时间需要 15 分钟。
package com.willhonor.test.useApplicationContext3LookupOrReplaceMethods;public interface FFruit { void say();}
package com.willhonor.test.useApplicationContext3LookupOrReplaceMethods;public class FApple implements FFruit { public void say() { System.out.println(String.format("fapple, 苹果[%d]", new Object[] { this.hashCode()})); }}
package com.willhonor.test.useApplicationContext3LookupOrReplaceMethods;import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;public class PersonA_use_lookup_method implements ApplicationContextAware{ private ApplicationContext context; public void eatFruit() { FFruit fruit = getAFFruit(); if (fruit != null) { fruit.say(); }else { System.out.println("没有水果吃"); } } public FFruit getAFFruit() { // 每次从 bean工厂获取一个 apple return (FFruit) context.getBean("apple"); } // 保存 applicationContext 引用 public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.context = applicationContext; }}
package com.willhonor.test.useApplicationContext3LookupOrReplaceMethods;import org.junit.Test;import org.springframework.context.support.ClassPathXmlApplicationContext;/** * 元素 lookup-method 使用 * @author jokee * */public class Test_Test_1 { @Test public void test_use_lookup_method() throws Exception { String pathA = "com/willhonor/test/configs/application.d.xml"; String[] path = new String[] { pathA}; ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(path); // PersonA_use_lookup_method persona = (PersonA_use_lookup_method) context.getBean("persona"); persona.eatFruit(); persona.eatFruit(); persona.eatFruit(); persona.eatFruit(); }}
...#此处省略 spring 日志打印...fapple, 苹果[226170135]fapple, 苹果[381707837]fapple, 苹果[589446616]fapple, 苹果[1321640594]
package com.willhonor.test.useApplicationContext3LookupOrReplaceMethods;import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;public class PersonA_use_lookup_method{ public void eatFruit() { FFruit fruit = getAFFruit(); if (fruit != null) { fruit.say(); }else { System.out.println("没有水果吃"); } } /** 方法返回 null,别慌,IOC 容器会帮我们覆盖这个方法 */ public FFruit getAFFruit() { return null; }}
...#此处省略 spring 日志打印...fapple, 苹果[710714889]fapple, 苹果[551734240]fapple, 苹果[1757293506]fapple, 苹果[687780858]
4.0.0 com.willhonor todos 0.0.1-SNAPSHOT spring-1.2.6 org.springframework spring-context 1.2.6 org.springframework spring-webmvc 1.2.6 org.springframework spring-jdbc 1.2.6 org.springframework spring-aop 1.2.6 javax.servlet servlet-api 2.3 org.mariadb.jdbc mariadb-java-client 2.3.0 junit junit 4.12 cglib cglib 2.1_3
转载地址:http://ajlsi.baihongyu.com/