0

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:

<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)?

6
  • 2
    What will happen if you test it before posting it as a question? Commented Aug 16, 2015 at 15:46
  • I wrote - "this config does not work"!!! My question is in class "wondering". I wonder: is it possible to make it work without setter/constructor or annotation. In python you can overwrite property directly. Commented Aug 16, 2015 at 15:48
  • The "actually (t)his config does not work" sounds like "I tested it" to me... Commented Aug 16, 2015 at 15:49
  • The wrong results are the answer. Commented Aug 16, 2015 at 16:01
  • @GoodBadandUgly you said "it is possible". Really? Can you post an example? Commented Aug 16, 2015 at 16:09

2 Answers 2

2

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.

<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; } } 
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Here's a detailed explanation: http://www.mkyong.com/spring/spring-auto-scanning-components/

4 Comments

OP's question is not about adding an annotation for this case.
That's true -- I guess I should have been explicit and said "no, not possible, but you can do this..."
Please edit your post and add that part in order to convert it into a valid answer :)
Yes) I know about annotations)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.