`
ponlya
  • 浏览: 159746 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

Spring3之 bean Method injection

阅读更多

Method injection(方法注入

bean都是singleton类型的。如果一个singleton bean要引用另外一个singleton bean,或者一个非singleton bean要引用另外一个非singleton bean时,通常情况下将一个bean定义为另一个bean的property值就可以了。不过对于具有不同生命周期的bean来说这样做就会有问题了,比如在调用一个singleton类型bean A的某个方法时,需要引用另一个非singleton(prototype)类型的bean B,对于bean A来说,容器只会创建一次,这样就没法在需要的时候每次让容器为bean A提供一个新的的bean B实例。

官方建议:You can make bean A aware of the container by implementing the ApplicationContextAware interface, and by making a getBean("B") call to the container ask for (a typically new) bean B instance every time bean A needs it.

http://blog.csdn.net/zml2004/archive/2006/04/15/664309.aspx例子

Lookup Method Injection 

 

 

<!--EndFragment-->

com.spring305.test.methodInjection.RandomT.java

public class RandomT{

    private int num = (int)(100*Math.random());
    public void printRandom(){
        System.out.println("随机数是"+num);
    }
}

 

com.spring305.test.methodInjection.HelloRandom.java

//一个代理接口
public interface HelloRandom {
	
	public RandomT getRandom();
	public abstract RandomT createRandom(); // 这个方法最为重要,是方法注入的关键
	
}

 

com.spring305.test.methodInjection.HelloAbstract.java

public abstract class HelloAbstract implements HelloRandom {

	private RandomT random;
	public void setRandom(RandomT random) {
		this.random = random;
	}

	public abstract RandomT createRandom();

	@Override
	public RandomT getRandom() {
		// TODO Auto-generated method stub
		return this.random;
	}
}

 

src/methodInjection.xml

 <!-- 方法注入-->
     <bean id="myRandom" class="com.spring305.test.methodInjection.RandomT"  scope="prototype" />
     <!--  scope="singleton" -->
     <bean id="helloRandom" class="com.spring305.test.methodInjection.HelloAbstract" >
           <lookup-method name="createRandom" bean="myRandom"/>
           <property name="random">
                   <ref local="myRandom" />    
           </property>
    </bean>

 Test

//@Test
public void testMethodInjection(){
        ApplicationContext context = new ClassPathXmlApplicationContext("methodInjection.xml");
         HelloRandom helloRandom1 = (HelloRandom)context.getBean("helloRandom");
         System.out.println("下面两个实例没有采用方法注入");
         RandomT r1 = helloRandom1.getRandom();
         RandomT r2 = helloRandom1.getRandom();
         System.out.println("Random 的两个实例是否指向同一个引用:" + (r1 == r2));
         r1.printRandom();
         r2.printRandom();
         System.out.println();
         System.out.println("下面两个实例采用方法注入");
         HelloRandom helloRandom = (HelloRandom)context.getBean("helloRandom");
         RandomT r3 = helloRandom.createRandom();
         RandomT r4 = helloRandom.createRandom();
         System.out.println("Random 的两个实例是否指向同一个引用:" + (r3 == r4));
         r3.printRandom();
         r4.printRandom();
}

 

另官方没有给这种Lookup方法注入而是提供了:Arbitrary method replacement方法替换:

com.spring305.test.methodInjection.MyValueCalculator.java

public class MyValueCalculator {

	public String computeValue(String input) {
		return input+"_"+(int)(100*Math.random());
	}

}

 

com.spring305.test.methodInjection.ReplacementComputeValue.java

public class ReplacementComputeValue implements MethodReplacer {

	@Override
	public Object reimplement(Object obj, Method method, Object[] args)
			throws Throwable {
		String input = (String) args[0];
		input += "123";
		
		return input;
	}
}

 xml中再加上:

  <bean id="myValueCalculator" class="com.spring305.test.methodInjection.MyValueCalculator">
	<!-- arbitrary method replacement -->
	<replaced-method name="computeValue" replacer="replacementComputeValue">
		<arg-type>String</arg-type> 
	</replaced-method>
	<!-- <replaced-method name="computeValue" replacer="helloReplacer"/> -->
</bean>
<bean id="replacementComputeValue" class="com.spring305.test.methodInjection.ReplacementComputeValue"/>

 

测试:

@Test
	public void testMethod(){
		 ApplicationContext context = new ClassPathXmlApplicationContext("methodInjection.xml");
		 ReplacementComputeValue reValue = context.getBean("replacementComputeValue",ReplacementComputeValue.class);
		 
		 MyValueCalculator myValueCalculator = context.getBean("myValueCalculator",MyValueCalculator.class);
		 System.out.println(myValueCalculator.computeValue("add"));;
		 
	}

 

 

分享到:
评论

相关推荐

    Getting.started.with.Spring.Framework.2nd.Edition1491011912.epub

    Chapter 8 - Messaging, emailing, asynchronous method execution, and caching using Spring Chapter 9 - Aspect-oriented programming Chapter 10 – Spring Web MVC basics Chapter 11 – Validation and data ...

    spring1.2学习心得分享

    资源释放:&lt;bean destroy-method=""/&gt;仅对单例对象有效 (2)IoC概念 Inversion of Control 控制反转或控制转移 Don't Call Me,We will call you! 控制权:对象的创建和调用关系的控制. (3)DI概念 Dependecy ...

    spring学习心得

    资源释放:&lt;bean destroy-method=""/&gt;仅对单例对象有效 (2)IoC概念 Inversion of Control 控制反转或控制转移 Don't Call Me,We will call you! 控制权:对象的创建和调用关系的控制. (3)DI概念 Dependecy ...

    Spring的学习笔记

    一、 Spring配置hibernate3的SessionFactory 30 (一) xml形式的SessionFactory 30 (二) annotation注解方式的SessionFactory 30 二、 引入hibernate所需要使用的jar 31 (一) 基本jar 31 (二) 加入annotation功能的...

    spring1.1开发理解

    资源释放:&lt;bean destroy-method=""/&gt;仅对单例对象有效 (2)IoC概念 Inversion of Control 控制反转或控制转移 Don't Call Me,We will call you! 控制权:对象的创建和调用关系的控制. (3)DI概念 Dependecy ...

    spring-boot-reference.pdf

    17. Spring Beans and Dependency Injection 18. Using the @SpringBootApplication Annotation 19. Running Your Application 19.1. Running from an IDE 19.2. Running as a Packaged Application 19.3. Using the...

    Manning.Spring.in.Action.4th.Edition.2014.11.epub

    2.4.3. Initializing a bean with constructor injection 2.4.4. Setting properties 2.5. Importing and mixing configurations 2.5.1. Referencing XML configuration in JavaConfig 2.5.2. Referencing Java...

    spring2.5 学习笔记

    一、 Spring配置hibernate3的SessionFactory 30 (一) xml形式的SessionFactory 30 (二) annotation注解方式的SessionFactory 30 二、 引入hibernate所需要使用的jar 31 (一) 基本jar 31 (二) 加入annotation功能的...

    springframework.5.0.12.RELEASE

    Exporting a lazily initialized bean (which implements SelfNaming and is annotated with ManagedResource annotation) gives IllegalStateException [SPR-17592] #22124 MockHttpServletRequest changes Accept-...

    spring-framework-reference-4.1.2

    3. New Features and Enhancements in Spring Framework 4.0 ............................................ 17 3.1. Improved Getting Started Experience .........................................................

    myspringlearning:Spring学习项目

    Spring学习项目IOC依赖的jar包 aspect2 dbcp hibernate jdom junit4 mysql pool2 spring slf4j注入类型setter(重要)Setter-based dependency injection构造方法注入 Constructor-based dependency injectionbeans....

    apache-tomcat-9.0.17.rar

    This chapter covers the Spring Framework implementation of the Inversion of Control (IoC) [1] principle. IoC is also known as dependency injection (DI). It is a process whereby objects define their ...

    spring-framework-reference4.1.4

    3. New Features and Enhancements in Spring Framework 4.0 ............................................ 17 3.1. Improved Getting Started Experience .........................................................

    struts1和struts2的区别

    答案是使用IoC(反转控制,Inversion of Control),也叫“依赖注入(Dependency Injection)”的模式(想更多地了解这方面信息请看Martin Fowler的文章http://www.martinfowler.com/articles/injection.html)。...

Global site tag (gtag.js) - Google Analytics