Using new in Spring framework applications?
开发者_C百科Is it forbidden or not a best practice to create objects using new. Creating objects means like Helper objects for some specific tasks that are no way related to the request, but are just used to perform some background tasks like reading a local file, database etc
- It's not forbidden
- It's not a good practice to instantiate stateless components (like helpers), because you are creating unnecessary instances
- All spring beans "live" in the application context, and it is the one that instantiates them, not you. So if you want to be able to inject dependencies into your objects, let them be spring-managed - i.e. don't instantiate with
new
. - Typically, only value objects (
User
,Address
,AccountInfo
, etc) are instantiated by you (usingnew
) - There is some "magic" that allows you to have both dependency injection and instantiation using
new
. It is the@Configurable
annotation. It uses AspectJ weavers that plug to the VM. But it is not something to consider until there are no alternatives. (the last sentence is my opinion)
The Spring framework itself supports designing you applications in an object oriented way (i.e. by minimizing the impact of using interfaces or have as little dependencies between classes as possible). In the application context you create a static environment, meaning you instantiate object structure the way you need them to be in your application.
Examples for objects that are usually instantiated in the Spring context:
- Database connections
- Service classes
- Page controllers etc.
These are all static resources that don't directly change during your applications lifecycle (which is why you can instantiate them in a static context).
If you just have an object that gets all it's information dnymically during runtime (e.g. from a web request or another file) you can't instantiate them in a Spring context at all. Don't forget that Spring wants and should be as unobtrusive as possible so why should it be forbidden to use anything that you used before?
精彩评论