Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
106 views
in Technique[技术] by (71.8m points)

java - Role of new keyword in Spring Framework

In the Spring Framework, it seems like beans are the preferred way of creating objects to use in business logic.

[Dependency injection] is a process whereby objects define their dependencies, that is, the other objects they work with, only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. The container then injects those dependencies when it creates the bean. This process is fundamentally the inverse, hence the name Inversion of Control (IoC), of the bean itself controlling the instantiation or location of its dependencies by using direct construction of classes, or a mechanism such as the Service Locator pattern.

So from my simple understanding, the difference is something like this:

// Plain ol' Java
Foo f = new Foo();

// Using beans in Spring Framework
Foo f = FooFactory.get();

Is it an oversimplification to say that as a rule, in methods outside of @Configuration classes and @Bean definitions, developers should only get objects using beans? Specifically, in the case where I want a fresh object, should I inject a prototype bean instead of using the new keyword directly?

One example of code where I'm not sure I'm following Spring conventions is shown below.

// Construct a new object that will be created in the database
RecordDto record = new RecordDto();

// Or should I be using some bean factory?
RecordDto record = RecordDtoFactory.get();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Please read this Article from beloved martin fowler. I think the IOC concepts is useful when some component in your application has a dependency to other component for some functionality to complete. IoC container will be responsible for managing creation and lifecycle of software components and also inject them in dependent components instead of manually get access to these components instances.

For example, when some Service require an instance of DAO, it will get it from container instead of creating it.

But in case of DTO, they will just hold the data and that is not a real dependency. So I think using "new" is better in this case.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...