I am studying for the Spring Core certification and I have the following doubt related how can Spring instantiate classes with private constructors (such as Singleton pattern) or how can instantiate objects from Factories (that are not the Spring context).
For example I have the following singleton factory:
public class AccountServiceSingleton implements AccountService {
private static AccountServiceSingleton inst = new AccountServiceSingleton();
private AccountServiceSingleton() { ... }
public static AccountService getInstance() {
// ...
return inst;
}
}
This is a singleton factory because it build a private static object builded with a private constructor and I have a public method to get this object.
So I think that the problem how can Spring build this object? depends on the fact that that the constructor is private so I can't do something like this in my Java configuration class
@Confguration
public class ApplicationConfig{
@Bean
public AccountServiceSingleton accountServiceSingleton(){
return new AccountServiceSingleton();
}
}
because I can't access to the private AccountServiceSingleton() constructor.
At the same time I can't use the equivalent XML configuration for the same reason.
Have I understand what is the problem or am I missing something?
I think that I am missing something because on the documentation I read that I can use the following 2 solutions for the previous problem:
Use a @Bean method in @Configuration class: so, reading it, I think that the previous Java configuration class work...but why?
XML factory-method attribute in the XML configuration, searching online I found that have to be something like this, but how can I use this to configure the previous AccountServiceSingleton bean in an XML configuration?
Tnx