0

I was reading Spring 3.0 documentation and I came to the sentence -

Annotation injection is performed before XML injection, thus the latter configuration will override the former for properties wired through both approaches.

Next the question came to my mind: If I use an annotation in a bean (like @Service("myService")), now I am using the other bean and it uses "myService", and "myService" would be injected through XML configuration.

Would this work? I tried but it is giving me

BeanCreationException (Cannot resolve reference to bean 'myService' while setting bean property 'myService')

Later, I went through this question Wiring Spring bean through annotations and xml context, but in the solution it is told that "Just leave all your annotated fields unspecified, and they'll get injected auto-magically." (I didn't try out this solution)

But what if I want to specify all annotated fields, like I specified @Service annotation above? Any suggestions??

Community
  • 1
  • 1
Nandkumar Tekale
  • 16,024
  • 8
  • 58
  • 85

2 Answers2

0

You need to autowire your constructor like below...

@Autowired(required=true)
public UserService(DataSource dataSource){
    this.userDS = new UserDS(dataSource);
}

So, in the above code the DataSource will be injected in the UserService automatically.

nwinkler
  • 52,665
  • 21
  • 154
  • 168
kandarp
  • 4,979
  • 11
  • 34
  • 43
  • 1
    Nonsense. This question has nothing to do with constructor injection. Constructor, method and field injection are three different versions of doing the same thing, but this problem can be solved using any of these. – Sean Patrick Floyd Mar 22 '12 at 07:26
0

I figured out the answer, it works very well. Actually I forgot to add tag in xml configuration. We need to add this tag in each config file i.e. if you have written config file for service layer beans, add tag for service layer annotated beans. Similar for dao and controller layers.

Nandkumar Tekale
  • 16,024
  • 8
  • 58
  • 85