英文:
Java Spring Framework. Declare classes as bean only
问题
我正在学习Java Spring,并与解决一个问题同时进行。
我的问题是:
我能够拥有一组仅被定义为Beans的类吗(而不在Java源代码中声明它们)?
当应用程序运行时,它将仅对Beans中可用的已声明类进行计算。
因此,例如,我有类A、B、C的Beans;但我在Java代码中没有针对这些类的声明。我可以将它们组合在一个名为DocumentationVersionSpecificTag的接口下。
这种方法可行吗?
英文:
I am learning Java Spring in parallel with tackling a problem.
My question is:
Can I have a pool of classes defined as beans only (without them declared in the JAVA source)?
When the application runs it will do computations only on the declared classes available in the beans.
So for instance I have beans for the classes A, B ,C; But I have no declaration in the java code for this classes. I may group them together under an Interface say DocumentationVersionSpecificTag
Is this approach feasible ?
答案1
得分: 2
你正在尝试使用@Autowired
来注入不在源代码中的对象,你可以通过配置类实现这一点,配置类是一个被@Configuration
注解标记的类,你可以在其中将这些类配置为beans,使用@Bean
:
@Configuration
public class ProjectConfiguration{
@Bean
public A configureA(){
return new A(); // 使用你想要的合适的构造函数
}
@Bean
public B configureB(){
return new B(); // 使用你想要的合适的构造函数
}
@Bean
public C configureC(){
return new C(); // 使用你想要的合适的构造函数
}
}
然后,你可以使用@Autowired
来注入这些类:
@Autowired
A a;
更多细节,请查看此链接。
英文:
You are trying to inject objects that are not in your source code using @Autowired
, you can achieve this using a configuration class, a class annotated with @Configuration, and configure these classes as beans in it, using @Bean:
@Configuration
public class ProjectConfiguration{
@Bean
public A configureA(){
return new A(); // use the suitable constructor you want
}
@Bean
public B configureB(){
return new B(); // use the suitable constructor you want
}
@Bean
public C configureC(){
return new C(); // use the suitable constructor you want
}
}
After you can inject these classes with @Autowired
:
@Autowired
A a;
For more details, see this link.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论