Best practice applicationContext injection in Spring3

As in the heading above, I'm confused about the minus pros between injecting applicationContext with @Autowired annnotation or implementing the ApplicationContextAware interface in a singleton spring bean.

Which one do you prefer in which cases and why? Thanks.

+6
source share
4 answers

Actually, both are bad. Both of them bind your application to the Spring framework, thus inverting the whole concept of control inversion. In an ideal world, your application should not be aware of managing with ApplicationContext in general.

Once you decide to violate this principle, it really doesn't matter how you do it. ApplicationContextAware is an obsolete version that has been since at least version 2.0 . @Autowired is a newer mechanism, but they work in much the same way. I would probably go with ApplicationContextAware because it semantically makes it clear what is at stake.

+9
source

As @Sean Patrick Floyd points out, the need for ApplicationContext is often due to poor design. But sometimes you have no other choice. In such cases, I prefer to use @Autowired because I enter all the other properties. So, if I use @Autowired to inject MyRepository, why can't I use it for ApplicationContext or any other Spring bean?

I only use Spring interfaces for those things that I cannot do with annotations, like BeanNameAware.

+2
source

If you need to get a prototype in a singleton then you can use the injection method. Basically, you create an abstract method that returns the object you want, and spring will return a prototype every time you call this method. You define a "search method" in the spring configuration. Here are some links: http://docs.spring.io/spring/docs/1.2.9/reference/beans.html#beans-factory-method-injection http://java.dzone.com/articles/method-injection -spring

+2
source

Since you are not distributing any of the spring classes, your application is always separate from the framework . In most cases, you do not need to enter ApplicationContext like this, but you will need to enter beans defined in ApplicationContext .

The best case is to always keep the minimum minimum, for now and if you do not have any specific requirements, and it is very simple with spring.

So either

  • Annotate your beans and scan them in the application context , and then use @Autowire to connect them.

  • Use application context to post your bean options (old xml style settings). You can also use @Autowire with this approach.

If you want to control the life cycle of a bean, you can read the API and configure it, but most of the time these general settings will do the job.

Here are some examples.

0
source

Source: https://habr.com/ru/post/910459/


All Articles