Java Spring Framework。仅将类声明为bean。

huangapple go评论66阅读模式
英文:

Java Spring Framework. Declare classes as bean only

问题

我正在学习Java Spring,并与解决一个问题同时进行。
我的问题是:
我能够拥有一组仅被定义为Beans的类吗(而不在Java源代码中声明它们)?
当应用程序运行时,它将仅对Beans中可用的已声明类进行计算。

因此,例如,我有类ABC的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.

huangapple
  • 本文由 发表于 2020年9月22日 17:15:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/64006653.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定