mps98
mps98

Reputation: 93

How to avoid the use of Spring annotations in my java beans and use them only in the configuration class?

I'm new in Spring and this is my first post here, I'm starting to use spring annotations, I was able to cofigure my project using XML configuration and now I'm able to configure it using only annotations and avoiding XML.

But my current need is to avoid the use of annotations in my java classes (beans) and use it only in my AppConfig.java class which I use to configure Spring.

This is my current working configuration:

AppConfig.java

@Configuration
@ComponentScan(basePackageClasses= {BlocBuilder.class,... all my classes go here})
public class AppConfig {


  @Bean
  @Scope("prototype")
  public BlocBuilder blocBuilder(){ 
      return new BlocBuilder();
  }

}

And this is one of my java classes.

BlocBuilder.java

public class BlocBuilder {

@Autowired
@Qualifier("acServices")
private SomeInterface someInterface;

public SomeInterface getSomeInterface() {
    return someInterface;
}
public void setSomeInterface(SomeInterface someInterface) {
    this.someInterface = someInterface;
}

What I want to achieve is to avoid the use of annotations in my classes for example in my BlocBuilder.java class I don't want to have annotations and move them to my config class.

How can I manage it?

Any help whould be really appreciated.

Upvotes: 2

Views: 1098

Answers (2)

duffymo
duffymo

Reputation: 308743

I wouldn't recommend a config class. It'll couple all your beans together.

Spring configuration doesn't need to be an all or nothing thing: annotations or XML. You can mix and match as you choose. Put annotations in the classes you want and use XML for the rest.

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213213

Constructor injection is what you're looking for. Create a 1-arg constructor in BlocBuilder which takes SomeInterface type argument. And then in config class, pass it as argument:

@Configuration
@ComponentScan(basePackageClasses= {BlocBuilder.class,... all my classes go here})
public class AppConfig {

  @Bean
  public SomeInterface someInterface() {
      return new SomeInterfaceImpl();
  }

  @Bean
  @Scope("prototype")
  public BlocBuilder blocBuilder(){ 
      return new BlocBuilder(someInterface());
  }
}

Upvotes: 4

Related Questions