Colin Riddell
Colin Riddell

Reputation: 427

Spring: Should I use @Service and then @Autowired it, OR @Component AnnotationConfigApplicationContext

I've got a client class that I want to be able to use anywhere. A singleton would work, I think.

Should I:

Annotate my client class with @Service and then @Autowired it anywhere I want it?

OR

Create a @Configuration thingy that has a method that has a @Bean to get a new instance of it, and then do the annoying new AnnotationApplicationContext() thing to get the context then get my client bean from that?

I just feel like option 1 is a lot easier and it works, but I get the impression that creating a Bean is the "more correct" way, but I don't understand why - it's definitely not easier. Can someone explain? Is there anything wrong with the first option?

Also, any really, really simplified explanations on what the basic "rules" for this stuff are, would be great if anyone has that up their sleeve..

Thanks

Upvotes: 0

Views: 2183

Answers (2)

ifelse.codes
ifelse.codes

Reputation: 2389

You should mark your class as @Component and @Autowired it in the client class.

@Service is just a special form of @Component

Example

@Component 
Class AUsefullClass {
  void useFullMethod(){
      System.out.println("ooo");
  }
}

@Controller
Class MyController {

    @Autowired
    AUsefullClass instnceOfaUsefullClass;

    void anyMethod(){
        instnceOfaUsefullClass.useFullMethod();
    }
}

Upvotes: 1

GnanaJeyam
GnanaJeyam

Reputation: 3170

If you have any dependency jar in your project. If it not a spring project, On that scenario You need to go for @Bean definition in your project. Option 2 - For this case.

Else If it is a spring project and you have control (write access) on that dependency, u can annotate it with @Service and use it by @Autowired in your Project. Option 1 Case

Upvotes: 2

Related Questions