问题
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.
回答1:
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());
}
}
回答2:
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.
来源:https://stackoverflow.com/questions/29365919/how-to-avoid-the-use-of-spring-annotations-in-my-java-beans-and-use-them-only-in