Issue
Iam trying to autowire an enum inside a spring Bean.I have not tried this before and not sure what is missing but when i do that i am getting parameter 0 of constructor in required a bean of type java.lang.string error. Please find below the code i have created.
public interface TokenGenerator{
String generateToken();
}
@Service
public enum TokenGeneratorImpl implements TokenGenerator{
INSTANCE;
private string token;
public string generateToken(){
if(token == null){
token="new token";
}
return token;
}
}
@Service
public class ConnectionService {
@Autowired
private TokenGenerator generator
public void getConnection(){
for(int i =0; i< 1000; i++){
Thread t = new Thread(() -> generator.generateToken());
t.start();
}
}
}
There are two issues: 1) Autowiring is not working and I am getting
parameter 0 of constructor in required a bean of type java.lang.string error
2) If i call directly the Enum and generate the token then i found that this code is not thread safe and want to understand how I can make it thread safe
Solution
By autowiring the TokenGeneratorImpl, you are trying to instantiate an ENUM which is not possible
https://stackoverflow.com/a/36710397/5001937
For 2nd Point https://stackoverflow.com/a/2531998/5001937
Answered By - Suraj
Answer Checked By - Robin (JavaFixing Admin)