Search code examples
javaspringsingletonprototype

How to get only one prototype bean in one method invocation?


I have a ptototype bean autowired in a singleton bean. To get different bean of the prototype bean, I marked it with proxyMode. Then, the side effect is huge: I always get more than one instances.

Here is my sample code:

@Service
@Slf4j
@Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class Duplicate {
public void serve() {
    log.error("{}", this);
}

public Duplicate get() {
    return this;
}
}

and

@Slf4j
@Service
public class Singleton {
@Autowired
private Duplicate d1;

public void serve(){
    Duplicate duplicate = d1.get();
    log.warn("d1 - 0 = {}", duplicate);
    log.warn("d1 - 1 = {}", duplicate);
    duplicate.serve();
}
}

and a UT case:

@Autowired
private Singleton singleton;
@Test
public void testOnScope(){
    singleton.serve();
}

The output is so weired to me:

Singleton - d1 - 0 = Duplicate@14f7e21a
Singleton - d1 - 1 = Duplicate@2bd9722
Duplicate - Duplicate@544cd64b

The memory addresses are totally different!

How should I modify my code to achieve the goal?


Solution

  • Do not use

    ScopedProxyMode.TARGET_CLASS
    

    use @Lookup instead.

    I post a blog public, but it's in Chinese. https://www.jianshu.com/p/eee4a785cadc