2

I am trying to learn some spring through reading the broadLeaf.

Why some broadLeaf use ApplictionContext.getBean() instead of @Autowired annotation?

Roman Pokrovskij
  • 9,449
  • 21
  • 87
  • 142
  • 3
    Possible duplicate of [What's the difference between @Autowired and getting a bean from the application context?](https://stackoverflow.com/questions/9255606/whats-the-difference-between-autowired-and-getting-a-bean-from-the-application) – Muhammad Waqas Feb 01 '19 at 10:19

2 Answers2

5

你好!

Fundamentally they are intended to do the same thing which is getting a bean from the spring container (i.e ApplicationContext) to use. You can think that @Autowired will actually do the work done by ApplictionContext.getBean() behind scene.

The differences are that when using ApplictionContext.getBean() , developers are in charge of the whole process by themselves .They have to make sure they get the correct beans by manually invoke getBean() with the correct parameters. But when using @Autowired , developer don't need to do this process manually. Instead , they just need to declare what beans they want and Spring will get these beans for them. So this is somehow the spirit of Inversion Of Control (IOC) as the responsibility of controlling of the above mentioned tasks are inverted and shifted from developers to the framework.

As best practices , we should always use @Autowired first. Not only it is more convenient , less error prone , but also our domain codes will not depend on the Spring framework class (i.e ApplictionContext) , which make our codes look more clean.

If you come to the situation that @Autowired cannot fulfil your requirements as you need to have the most flexibility to get a bean , then check if ApplictionContext can help you at that time.

Ken Chan
  • 84,777
  • 26
  • 143
  • 172
0

Example

@Service
public class Car {
  @Autowired
  public Person driver;
}

@Autowired is respected on wiring of the Bean Car. The Field get filled directly after creating the instance by the default constructor (new Car()) throu Spring.

ApplictionContext.getBean()

Is the same but: you must call it by your own code.

@Autowired is the same as @Inject. The difference is not the functionality but the design. Spring uses the Context and Dependency Injection (CDI) by @Inject as part of the principle of the Inversion of Controll (IoC) and should be preferred. Thats why

Grim
  • 1,938
  • 10
  • 56
  • 123