spring method injection lookup method injection

1. Stateless beans and stateful beans
 Once instantiated, stateless beans are added to the session pool and can be shared by all users. Even if the user dies, the lifetime of the bean is not necessarily over, it may still exist in the session pool for other users to call.
stateful beans    


Stateful session bean: Each user has its own unique instance. During the lifetime of the user, the bean maintains the user's information, that is, "stateful"; once the user dies (the end of the call or the end of the instance), the lifetime of the bean also ended. i.e. each user initially gets an initial bean.
That is to say, when a session ends, the life cycle of a bean ends, which is a stateful bean.

Stateless beans are generally configured in sigleton singleton mode

  2, lookup method injection
If a singleton mode Bean Boss has a property mode Bean Car, then want to get a new Car bean every time the boss is called? What to do. You must know that Boss is in singleton mode, it will only be created once, and properties will be injected once, that is to say, even if Car is in property mode, there will only be one same Car, because Boss will only be injected once.
If you want to achieve this purpose, you can make Boss implement the BeanFactoryAware interface, so that Boss can access the reference from the container. The getCar() method of Boss can be implemented as follows

public Car getCar(){
     return (Car) factory.getBean("car");
}

At the same time, spring ioc also provides a solution.

That is lookup method injection

First declare a MagicBoss interface

public interface MagicBoss {
    Car getCar();
}

Then implement it in the configuration file as follows

      < bean id = "car" class = "com.aowin.modle.Car" scope = "prototype" >
                    < property name = "brand" >< value > 红旗 </ value ></ property >
                    < property name = "price" >< value > 12 </ value ></ property >
               </ bean >

< bean id = "magicBoss" class = "com.aowin.modle.MagicBoss" >
                    < lookup-method name = "getCar" bean = "car" />
           </ bean >

In this way, every time it is called, magicBoss will get the latest Car from the container.
At the same time, it should be noted that the scope of Car cannot be singleton (the default is singleton, so it must be manually configured as a propoty). In this case, the above configuration still works, but the same Bean is taken out each time.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325472151&siteId=291194637