简体   繁体   English

如何在无参数构造函数中访问Spring bean?

[英]How can I access Spring beans in no-arg constructor?

@Component
public class MyClass {
    public MyClass() {
        SomeInterface something;

        // Spring magic that i don't know

        something.toString();
    }
}

What Spring magic do I need to use to inject a bean into "something"? 将bean注入“某物”中,我需要使用什么Spring魔术?

I also wouldn't mind if it was a field. 我也不介意这是否是一个领域。 It just has to be usable from within the constructor! 它只必须在构造函数中可用!

The basic rules also apply to Spring: 基本规则也适用于Spring:

  • to construct an object, Spring needs to invoke the constructor 要构造一个对象,Spring需要调用构造函数
  • Spring can't call a method of an object or set one of its fields if it isn't constructed yet 如果尚未构造,Spring不能调用对象的方法或设置其字段之一
  • so if you want to access a field set by Spring , you can't do that from the constructor, unless the value is passed as argument to the constructor. 因此,如果您想访问Spring设置的字段,则无法从构造函数中执行此操作,除非将值作为参数传递给构造函数。

This thus leaves two choices: 因此,这留下了两个选择:

  1. constructor injection: 构造函数注入:

     @Autowired public MyClass(SomeInterface something) { // use something } 
  2. post-construct method, called after all the injections have been done, whatever the way: post-construct方法,在完成所有注入后以任何方式调用:

     @Autowired private SomeInterface something; @PostConstruct private void initialize() { // use something } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 春季:@Configuration中缺少默认或无参数构造函数 - Spring: Default or no-arg constructor is missing in @Configuration Spring Beans - 如何将null作为构造函数arg连接? - Spring Beans - how to wire null as a constructor arg? init 方法在 Spring 中工作是否需要无参数构造函数(忽略默认构造函数,因为我有一些参数构造函数)? - Is no-arg constructor(ignore default constructor as I have some arguments constructor) necessary for init method to work in Spring? Vaadin Spring Projekt需要no-arg构造函数,仅在tomcat而不是本地 - Vaadin Spring Projekt expects no-arg constructor, only on tomcat not local 配置类中的Spring MVC Default或no-arg构造函数 - Spring MVC Default or no-arg constructor in configuration classes 在java spring beans中构造函数arg中的ref有什么用? - What is the use of ref in constructor-arg in java spring beans? 我可以将ApplicationContext定义为Spring XML配置中的构造函数arg吗? - Can I define ApplicationContext as a constructor-arg in Spring XML configuration? 如何根据属性文件或环境变量参数化 spring 构造函数参数注入? - how can I parametrize the spring constructor-arg injection based on the property file or environmental variable? IllegalAnnotationsException:domain.NewsletterType没有无参数的默认构造函数 - IllegalAnnotationsException: domain.NewsletterType does not have a no-arg default constructor 春天:如何添加一个bean的属性作为构造函数arg - spring: how to add a property of a bean as a constructor arg
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM