-2

Does Spring create new instances of constructor parameters of the same type for different beans?

For example, I have two REST controllers:

First:

@RestController
@RequestMapping ("/getHwidData")
public class GetHwidDataController {

    private final ApiKeysDatabase apiKeysDb;
    private final BanwareDatabase banwareDb;

    @Autowired
    public GetHwidDataController(ApiKeysDatabase apiKeysDb, BanwareDatabase banwareDb) {
        this.apiKeysDb = apiKeysDb;
        this.banwareDb = banwareDb;
    }
}

Second:

@RestController
@RequestMapping ("/setHwidData")
public class SetHwidDataController {

    private final ApiKeysDatabase apiKeysDb;
    private final BanwareDatabase banwareDb;

    @Autowired
    public SetHwidDataController(ApiKeysDatabase apiKeysDb, BanwareDatabase banwareDb) {
        this.apiKeysDb = apiKeysDb;
        this.banwareDb = banwareDb;
    }
}

As you may see, both controllers' constructors are @Autowired, and both accept the same object types: an ApiKeysDatabase and a BanwareDatabase.

I have some caching and other instance-dependent stuff inside those *Database classes, so I'd like to know: when the two above-stated REST controllers are created, will their apiKeysDb and banwareDb fields be respectively equal (hold the same instance of the ApiKeysDatabase and BanwareDatabase objects respectively)? That is,

GetHwidDataController ctrlOne = ...
SetHwidDataController ctrlTwo = ...

assertTrue ctrlOne.apiKeysDb == ctrlTwo.apiKeysDb 
        && ctrlOne.banwareDb == ctrlTwo.banwareDb
German Vekhorev
  • 339
  • 6
  • 16
  • 1
    Depends on the bean. You can annotate each one to have different scopes: prototype, singleton, request, session, global session: https://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch04s04.html – duffymo Apr 16 '19 at 13:41
  • The caching and instance dependent stuff is a terrible idea. These should be shared singletons. – duffymo Apr 16 '19 at 13:42

1 Answers1

1

It depends on the type of the bean, the default scope is singleton so in that case, no, it is not going to create a new instance but it will use the same one.

You can change the scope of a bean with the @Scope annotation.

burm87
  • 768
  • 4
  • 17