1

I have started using Java configuration files for creating Spring beans using the @Bean annotation. I really like this method for some of my more complex classes especially classes that involve generics.

However, I find that the Java file is less readable than XML with respect to identifying beans and their ids. Especially where there are a mix of @Bean methods and non-bean generation helper methods.

I was hoping someone could point me to a good example of doing this in a readable fashion. Or if there is a reference implementation I could use as an example / guideline.

John B
  • 32,493
  • 6
  • 77
  • 98

2 Answers2

1

Best way i found dealing and specifying Beans in spring when dealing with complex constructs is using two simple annotations:

@Bean
@Qualifier

Great example of bean usage can be found here:

http://www.tutorialspoint.com/spring/spring_java_based_configuration.htm

And example with qualifier usage:

Spring: Attaching @Qualifer to Java-configured beans

Essentially you create a bean then you give it a unique name, using the qualifier tag. From there you can build up on it as you need it.

@Qualifier can be rather powerful.

Hope this helps.

Community
  • 1
  • 1
Aeseir
  • 7,754
  • 10
  • 58
  • 107
0

After doing this for a while I have found that I do indeed use Sotirios's suggestion. I find that I do one of two things:

@Bean(name = "someBeanName")
public MyClass blahBlahIsIgnored(){
   return new MyClass();
}

I use the above if I just need to create the bean but don't need to worry about referencing it too much. However, if I have gone through the effort of naming it, I usually take an additional step:

@Configuration
public class MyConfiguration{
  public static final String USER_RESOLVER = "someBeanName";

  @Bean(name = USER_RESOLVER )
  public MyClass blahBlahIsIgnored(){
    return new MyClass();
  }
}

This then allows the below:

@Autowired
@Qualifier(MyConfiguration.USER_RESOLVER)
private MyClass userResolver;
John B
  • 32,493
  • 6
  • 77
  • 98