Injecting java.util.Random on a constructor

code-injection, java, spring

Solution

You can do this:

@Autowired
public HiddenNumber(@Value("#{new java.util.Random()}") Random random, @Value("4")int maxNumberOfDigits) {
...
}

Problem

I have a class HiddenNumber with this constructor: ``` public HiddenNumber(java.util.Random random, int maxNumberOfDigits) { /* some code */ } ``` I´m trying to use annotations for DI as: ``` @Autowired public HiddenNumber(@Value("T(java.util.Random") random, @Value("4")int maxNumberOfDigits) { /* some code */ } ``` But it doesn't work. I also tried: ``` @Autowired public HiddenNumber(@Value("#{T(java.util.Random}") random, @Value("4")int maxNumberOfDigits) { /* some code */ } ``` If I do: ``` @Autowired public HiddenNumber(Random random, @Value("4") int maxNumberOfDigits) { /* some code */ } ``` And in the app-context.xml do: ``` <bean class="java.util.Random" /> ``` It works ok. But of course I prefer to do only annotations. What is the correct way to inject java.util.Random? Thanks.

Original source