【问题标题】:Best practice of injecting a non bean property注入非 bean 属性的最佳实践
【发布时间】:2018-07-04 08:35:39
【问题描述】:

我有一个对象,我想将其转换为弹簧单例,其中包含我想在初始化后注入的属性。该属性不能作为 bean 启动,我希望从代码中检索它。

public class BigObject{
    private SmallObject prop;
}

我添加了以下 bean:

<bean id="BigObject" class="com.cisco.cpm.lsd.SessionPublisher"
      scope="singleton" init-method="init"  destroy-method="destroy" lazy-init="true">                
</bean>

是否有初始化prop 的最佳实践方法?
我知道这可以通过属性工厂方法来完成

<property name="prop">
    <bean factory-bean="SmallObjectFactory" factory-method="getSmallObject"></bean>
</property>

但这需要我为该属性初始化添加一个新对象。有更好的解决方案吗?

【问题讨论】:

标签: java spring dependency-injection


【解决方案1】:

如果我正确理解您的问题,这样的事情应该可以工作。首先创建一个公开您的 SmallObject bean 的 @Configuration:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class YourConfiguration {
    @Bean
    public SmallObject getSmallObject() {
        // create a new SmallObject
        return new SmallObject();
    }
}

然后,在您希望注入 SmallObject 的 BigObject 中,您可以执行以下操作:

import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;

@Component
public class BigObject {
    private SmallObject smallObject;

    @Autowired
    public BigObject(SmallObject smallObject) {
        this.smallObject = smallObject;
    }
}

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-21
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多