Issue
Below is a class which uses the @Configuration annotation to create a Bean. I am slowly introducing Spring into a legacy Java application. I don't want to Spring-ify everything all at once - that would be crazy. I thought I'd start with one of the commonly used utility classes and I don't want Spring to create Beans for the three fields below (Enumerator, RandomDataGenerator, AliasMethodFactory). How do I turn off Autowiring for those fields? Spring is currently complaining that it can't find Beans for those (it's obviously trying to auto-wire them).
@Configuration
public class CustomRandom {
private Enumerator enumerator;
private RandomDataGenerator rDataGenerator;
private AliasMethodFactory amf;
@Bean
@Primary
public static CustomRandom buildRandom() {
return new CustomRandom(
new Enumerator(),
new RandomDataGenerator(
new MersenneTwister(System.currentTimeMillis() * Thread.currentThread().getId())
),
new AliasMethodFactory()
);
}
CustomRandom(Enumerator enumerator, RandomDataGenerator generator, AliasMethodFactory amf) {
this.enumerator = enumerator;
this.rDataGenerator = generator;
this.amf = amf;
}
//UNRELATED INSTANCE METHODS FOLLOW...
Solution
Seperate the class for the Bean and the Configuration of the Bean. Like this
@Configuration
public class CustomRandomConfiguration
{
@Bean
@Primary
public static CustomRandom buildRandom()
{
return new CustomRandom(
new Enumerator(),
new RandomDataGenerator(
new MersenneTwister(System.currentTimeMillis() * Thread.currentThread().getId())
),
new AliasMethodFactory()
);
}
}
and the bean:
public class CustomRandom
{
private Enumerator enumerator;
private RandomDataGenerator rDataGenerator;
private AliasMethodFactory amf;
public CustomRandom(Enumerator enumerator, RandomDataGenerator rDataGenerator, AliasMethodFactory amf)
{
this.enumerator = enumerator;
this.rDataGenerator = rDataGenerator;
this.amf = amf;
}
}
Answered By - Andreas Radauer