Spring @Autowired vs使用'new'关键字来创建Object [英] Spring @Autowired vs using 'new' keyword to create Object
问题描述
我正在学习Spring并构建一些实验应用程序。我很困惑在哪里使用@Autowired来创建Object。
I am learning Spring and building some experiment application. I am confused on where to use @Autowired for creating the Object.
我得到它促进松散耦合的部分,并且每次创建一个新的Object而不是什么是新关键字。
I get the part that it promotes loose coupling and also does create a new Object Every time as opposed to what 'new' keyword do.
但我们应该如何处理我们需要在我们的应用程序中使用的第三方对象。例如,我正在使用休息API,我需要初始化三个类,类似这样的事情
But what should we do for the Third Party Objects which we need to use in our Application. For example I am consuming a rest API for that I need to Initialise three Classes , something like this
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
这段代码正在为RestTemplate,HttpHeaders和HttpEntity创建新的对象。使用此代码,每次调用其余API时,它都会创建三个新对象。这是正确的方法还是我应该标记它们@Autowired。请详细说明。
This chunk of code is creating new Objects for RestTemplate, HttpHeaders and HttpEntity. With this code it will create three new objects everytime I call the rest API. Is it the correct approach or should I mark them @Autowired. Please elaborate.
推荐答案
@Autowire
的典型用法是自动在初始化bean时,使用单例依赖项填充属性。无论是您的代码还是第三方类,都无关紧要。你需要考虑它是否是程序逻辑的一部分,或者它是否真的是一个应该被初始化一次并重用的依赖。
The typical use of @Autowire
is to automatically fill a property, when initializing a bean, with a singleton dependency. It does not matter if it's your code or a Third Party class. You need to consider if it is part of your program's logic or if it is really a dependency that should be initialized once and reused.
如果你的 RestTemplate
需要在每个交换
之前进行相同的初始化,然后你可以考虑使用 @Autowire
并在Spring的配置中初始化bean。从这个意义上说,它类似于 DataSource
。但是,如果您将其视为一个实用程序类,它被用作程序逻辑的一部分(如连接或文件),则不要将其视为 @Autowire
。它会使你的程序更加复杂而没有显着的收益。
If your RestTemplate
needs to have the same initialization before each exchange
then you can consider using @Autowire
and initialize the bean in Spring's configuration. In this sense it would be similar to a DataSource
, for example. But if you see it as an utility class that is used as part of the program's logic (like a connection or a file) then do not consider it for @Autowire
. It will make your program more complex without a significant gain.
这篇关于Spring @Autowired vs使用'new'关键字来创建Object的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!