如何避免在我的java bean中使用Spring注解而只在配置类中使用它们? [英] How to avoid the use of Spring annotations in my java beans and use them only in the configuration class?
问题描述
我是 Spring 新手,这是我在这里的第一篇文章,我开始使用 spring 注释,我能够使用 XML 配置来配置我的项目,现在我能够仅使用注释来配置它并避免XML.
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.
但我目前的需要是避免在我的 java 类(beans)中使用注解,并且只在我用来配置 Spring 的 AppConfig.java
类中使用它.
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();
}
}
这是我的 Java 类之一.
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;
}
我想要实现的是避免在我的类中使用注释,例如在我的 BlocBuilder.java
类中,我不想有注释并将它们移动到我的配置类中.
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.
我该如何管理它?
任何帮助都将不胜感激.
Any help whould be really appreciated.
推荐答案
构造函数注入正是您要寻找的.在 BlocBuilder
中创建一个 1-arg 构造函数,它接受 SomeInterface
类型参数.然后在配置类中,将其作为参数传递:
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());
}
}
这篇关于如何避免在我的java bean中使用Spring注解而只在配置类中使用它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!