Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
In my team lot of fights I see as some people using #JsonInclude annotated objects in DAO layer and some people argues to not to use and I could not able to find the reason for this.
Please anyone suggests.
Are the #Json annotations on DTO objects that you use to define your DAO interfaces? It might indicate that you reuse the same objects to define an external API like REST.
A consideration might be that if you reuse these objects, that you will couple the REST API to the DAO API. You need to consider if this is acceptable for you.
For applications that you have completely under control, it might be acceptable.
If you have clients that need a stable version of the REST API, you might want to use different DTO objects for your REST API (with #Json annotations) and for your DAO, so you can change your DAO's interfaces without having to change your REST API. But you need to maintain double classes and have extra mapping code to map between them.
Jackson does not force developer to link domain model with it's annotations. In most cases you can use MixIn feature and add annotation to given class, methods, properties in Runtime.
There is no "right" approach you can use in every project. Generally, it depends from: team, business requirements, used frameworks, etc.
If you want to show in REST API model as it is used for DB you can use Jackson annotations directly on given class as you probably do with Hibernate annotations. But in case you just want to show some part of a model in REST API you can create a separate model and use some mapping tools (Dozer, ModelMapper, MapStruct) or use MixIn feature, I mentioned about before, and reuse ORM model.
Definitely, you should use in a project one approach. Every class is annotated with Jackson or none of them. Using it partially makes a mess and it is hard to maintain project like this.
To make decision easier, you can read:
Domain Driven Design by Martin Fowler
Domain Driven Design and Development In Practice
Jackson/Hibernate, meta get methods and serialization
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 months ago.
Improve this question
Can a Plain Old Java Object have methods that deal with business logic other than just the getter/setter methods?
I see possibly mixed answers for this so is there no rigorous definition for this? I know a POJO cannot implement an interface, extend a class, and not use annotation.
You seem to be getting caught up in details of a formal definition that does not exist.
“POJO” is not a precise formal term. “POJO” is a catchy casual term coined by Martin Fowler, Rebecca Parsons, and Josh MacKenzie back in 2000.
The idea of a POJO is an object that is not enmeshed in a complicated framework. Any experienced Java programmer should be able to read and understand the source code of a POJO without needing to learn some framework, and without needing to look up third-party documentation.
Annotations
So, a POJO will generally have few annotations only because because Java bundles few annotation classes. Most annotations come from external frameworks. So if we are avoiding the complications of external frameworks, we are avoiding most annotations.
Personally, I would add an exception for one framework: Jakarta Bean Validation (Wikipedia). This framework is relatively simple, does not involve any elaborate involvement, and focuses on the validity/integrity of the POJO’s own internal field values. The validation rules are applied as annotations.
Logging might be another framework exception. And maybe Java Management Extensions (JMX) monitoring too. Notice that all three of my own personal choice in framework exceptions are focused on the POJOs themselves, as opposed to orchestrating some elaborate involvement with other objects.
Business logic
And, yes, a POJO can have business logic, especially regarding its own internal state, and regarding its need to communicate its changes with the outside world such as persisting data and notifying other interested parties.
Indeed, you can learn about:
Hexagonal Architecture by Dr. Alistair Cockburn(and related variations, Onion Architecture, etc.)
Domain-driven design (see book by Eric Evans)
… to see how you can use POJOs as domain objects (“business objects”, with core business logic) while keeping them separate and protected from various elaborate frameworks operating in other parts of your app.
Data-only objects
Some classes are intended to simply carry data. All such data-only classes are POJOs. But not all POJOs are data-only classes.
I suggest you learn about Data Transfer Objects and Value Objects, as kinds of data-only classes.
If the main purpose of your class is to communicate data transparently and immutably, use the records feature in Java 16+. In a record, by default, the compiler implicitly creates the constructor, getters, equals & hashCode, and toString.
And let me be clear: there is nothing wrong necessarily with elaborate complicated frameworks. They can be exquisitely useful, obviously. That's why they were invented. Each framework has a purpose and a place.
The term POJO was invented so that in discussions about programming and system architecture/design we can make the distinction between classes that are simple and not entwined versus those classes that are complicated and entwined.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
You often need to make a target object from a bunch of source ones.
I know the only one option - to make an upper-level synthetic class which contains required types as its fields and pass it as a source to Spring Converter. But maybe it's possible to do it easier?
Thanks in advance.
By default Spring seems not to offer an interface exposing any kind of functionality that will allow you to accept more than one source objects.
By definition the signature of the interface for the Converter only accepts a S which can then be converted over to T. It would be really nice, if Spring would offer in the future a interface that would accept more than one input objects (say, S, U) which would then be used to create a T but as of Spring 5.x this is still not present.
If you really want to use an implementation of the Converter interface you could do any of the following:
If you're instantiating yourself, you could very well pass in one or
objects through the constructor. This will mean that the
implementation class will start to effectively store state (which is
something that in my mind supersedes a simple converter's job).
Create a converter that will accept a carry object as it's source.
This pattern can be easily used to convert from two object into one
simply by using Spring Pair object (assuming that you use Spring
Data). Documentation pertaining to Pair can be found here.
Both the above should work fine, assuming that you really need to use a Spring specific converter (which is the case if you register them globally to the FormatterRegistry.
Now, assuming that the above is not the case really, there is nothing stopping you going native JDK and using an implementation of the BiFunction. In fact you can go ever further and make that class a Component meaning that you'll be able to inject it whenever you want. The trade-off in doing so? You'll lose the ability to register global converters, but hey if your project does not make any use of them the trade off is minimal (a note here that Converter implementations are thread safe).
Finally there is nothing stopping you of creating your own #FunctionalInterface that you'll use to perform conversions given any amount of input sources.
To sum up, no Spring does not offer an out of the box way to do so. It would have been nice but it seems it's not available.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm developing a Spring Boot MVC application and, after reading many guides and comments, I still have some doubts that I have not unmarked.
1: I do not want an anemic pattern, so I do not have a monolithic service where all the services are called each other, but these communicate only with repository instantiating entity, inside which I put the business logic, correct?
2: where to put the conversion functions entitiy-> dto? I read that someone puts them in the Controller, others in the Service, others on the same domain .. at the moment the cleanest solution and I prefer to have a Builder of the DTO that lends the entity input, okay I have contraindications?
3: polymorphism and inheritance: I have a service that composes some menu levels according to an attribute of the entity in question. I do not want to have blocks of if anywhere, I wanted to be able to put this logic in a single point, to instantiate the correct class (which I do not know a priori) and to exploit the polymorphism, how can I do? considered to involve service, entity and related logic ..
thank you so much
Your questions are more related to software design in general rather than specific to the Spring framework. Allowing the framework to dictate how to organize your code, has some downsides.
But to answer your questions:
Depending on how complex and interrelated your model is, there are different options, for the cases where there is not big interdependence between the entities in the model, the 3 layer approach is simple and good enough, but if your model is more complex, you could take a look into the concept of Aggregates, and keep the invariants hidden inside.
Constructing the DTO with the Entity as parameter is a good solution, whenever changes needs to be made to either the DTO or the Entity, the amount of code to maintain is not as much as with other approaches, it is not just about the conversion code, it is also about methods signatures, and all of the usages. This approach also follows the Dependency Inversion principle which states that low level modules (presentation in this case) should depend on high level policies (business logic) and not the other way around. But it is not the only valid solution, it always depends on your concrete case.
If you want to return an object from your service that can be an instance of different types, there are different ways to do so, a way to do so (but not the only one, and again, the best way always depends on your concrete case):
For the type control, one option would be to make the method return type an interface, and then have the possible different objects that can be returned to extend that interface.
For the construction of the different objects, you can encapsulate it inside of the service in a private function if that is the only place you are going to use it, or if you are going to use it in more places, then you could extract it to a factory and use it as a colaborator of the service. For the construction you won't be able to avoid the if checks, but outside the service, once you serve the different instances, then you won't need to do more if checks.
and finally in the service return the instance that you constructed, as it implements the interface, the compiler will still be happy about it.
Hope it helps!
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I know there's quite a bit out there on this topic, but I couldn't seem to find any that completely answers my questions. I was told to use a Service->DAO->Low level code architecture . I'm having a hard time wrapping my head around is the exact role of the Service class, will one Service class work for a Book DAO and also a user DAO? I was going to have a Service class for each, haveing the Service clas talk to the DAO, take the resulting string and store it in my Book class and User class, then send that object back to the Controller. In my thinking, the Service class is the high level class that delegates all the work to other classes. Thanks for your help.
A collection of service classes, known as a service tier, is responsible for carrying out the business logic of an enterprise application. Service classes usually don't map directly to DAOs, since they represent business operations that might involve a large number of domain objects. An example is an order-submission process, where the code responsible for accepting an order has to work with the objects representing orders, customer accounts, financial accounts, and inventory.
Separating the various business operations into different service classes is a design decision that depends on the complexity of the operations, how closely they're related, and so on. Some designers might decide that each business operation should be essentially a separate class (similar to the Command pattern), while others prefer a more comprehensive interface with a richer variety of methods.
The concept of a service tier exists to make sure that all of the business logic is stored in one place and not duplicated. Many modern systems will have several interfaces into the backend, such as a Web application (perhaps with Spring MVC Controllers), a SOAP or REST interface (perhaps with Jersey), and specialized adapters for legacy terminals or other systems. Making these interfaces all adapters around a common service tier ensures that they all behave in a consistent way and that any changes to the service tier are applied to all of the access interfaces.
In your particular case, since you're needing to ask, a single service object will probably be sufficient for your needs. It's always a good idea to list all of the service methods on a separate interface and code to that so that you can replace the implementation for testing or future upgrades.
Service class may be acting as a layer of abstraction so DAO or data layer is hidden from the "business layer".
The service may talk to multiple DAOs to perform a function in which case it's acting more of a Facade pattern, hiding the complexity of communicating with DAOs to perform the required functionality.
This sort of pattern is seen in the port and adapter or hexagonal architecture in that the business logic is insulated from lower level protocols.
http://c2.com/cgi/wiki?PortsAndAdaptersArchitecture
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
First let me note, that I use AspectJ and I like it, but what else can I do with it.
I know AspectJ can be/is used for Logging. In some cases it is used for Transaction controlling – mostly implemented in conjunction with annotations.
AspectJ can also be used to enhance classes with (code-generated) methods, like Spring Roo does.
But I believe AspectJ and AOP in general, can be used for more than: logging, transaction controlling, and simulation partial classes.
So what are other useful use cases for AspectJ and AOP?
permission check
interrupt action that takes too long
run action in separate thread or even in context of different process or event on other machine
monitoring
preparing any data / environment before call and processing results after call
opening / closing resources
EDIT
Although many years passed since I gave this answer I decided to add the following to make the answer more complete.
security check.
fixes of incorrect or behavior of API that you cannot change. For example boolean method that returns false in some conditions but should return true. You can fix this using AspectJ.
The Wikipedia entry gives you a few more examples (but not that many). Typically, Aspect Oriented Programing should be use only to implement simple behaviours that are not part of core concern of a class and are common to different classes. As soon as you begin to put too much logic in your aspects, the code becomes really unreadable.
The aspect you suggest (logging, transaction, ...) are the most commonly used. I would add security as well.
One can use AspectJ for enforcing some (design) rules.
like every controller method need some special annotations
every service/frontend/dto class must be located in a service/fronten/dto pacakge
more mature thinks like: checking that setters do not have any logic.
Inject Mocks in classes that otherwise would create new instances by using new.
Assume you have this code:
public void sendInvitationEmail(String address) {
InvitationEmail email = new InvitationEmail();
email.sendTo(address).send();
}
And need to replace email by an mock. Then you could use an Aspect (#Pointcut("call(InvitationEmail.new(..))")
) to "inject" a mock. -- #See Blog JMock and AspectJ by Daniel Roop, as well as Spring Roo`s #MockStaticEntityMethods (Mock Static Methods using Spring Aspect)