简体   繁体   English

没有构造函数和 setter 的 spring 注入

[英]spring injection without constructor and setter

I have the question.我有这个问题。 If my class has dependency like:如果我的班级有以下依赖项:

public class Test {
   public Depend depend;

   //Here methods
}

And it does not have setter for Depend property or constructor with Depend as argument, and it has no annotation for Spring but has xml config like:没有用于Depend属性的 setter 或以Depend作为参数的构造函数,并且它没有 Spring 的注释,但具有xml配置,例如:

<bean id="depend" class="xxx.Depend"></bean>

<bean id="test" class="xxx.Test">
   <property name="depend" ref="depend" />
</bean>

Is it possible to inject Depend into Test using such config (actually his config does not work. I just wonder - can I change smth to make it work not using annotations or setter/constructor)?是否可以使用这样的配置将Depend注入到Test 中(实际上他的配置不起作用。我只是想知道 - 我可以更改 smth 以使其不使用注释或 setter/构造函数工作)?

It is not possible without using annotations.不使用注释是不可能的。

Your current configuration needs some simple changes to make this work.您当前的配置需要进行一些简单的更改才能使其正常工作。 Annotate the depend field with @Autowired and enable component scanning.使用@Autowired注释depend字段并启用组件扫描。

Here's a detailed explanation: http://www.mkyong.com/spring/spring-auto-scanning-components/这里有详细的解释: http : //www.mkyong.com/spring/spring-auto-scanning-components/

Yes it is possible without annotations, but you would need to create a TestBeanFactory and then create an object of Test and set Depend yourself before returning it.是的,没有注释是可能的,但是您需要创建一个 TestBeanFactory 然后创建一个 Test 对象并在返回之前自己设置 Depend 。

<bean id="depend" class="xxx.Depend"></bean>
<bean id="testFactory" class="xxx.TestFactory">
    <property name="depend" ref="depend" />
</bean>

<bean id="test" factory-bean="testFactory" factory-method="createTest">
</bean>

Then your test factory would look something like this.那么您的测试工厂将看起来像这样。

public class TestFactory {
    private Depend depend;
    
    public setDepend(Depend depend) {
        this.depend = depend
    }

    public Test createTest() {
        Test test = new Test();
        test.depend = this.depend;
        return test;
    }
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM