When using Management Beans in Java, its interface is exposed through MBean Interface. But if there are various parameters to be exposed through MBean. And with different version of the system, many new parameters might be added or subtracted from the MBean, then it becomes very tedious to manage such system.
Is there any design pattern that can be used to avoid such problems ?
If you want things to happen dynamically, you've got to have some logical rule to dynamically determine which fields \ methods of the managed class should be exposed and which should not.
Now, you might be able to implement a Dynamic MBean (see a great explanatory example here) and use reflection to gather up-to-date information of the managed class. The reflected class info should then be filtered against the previously mentioned rule (hoping all other programmers follow it! I wouldn't count on it).
OK, so this isn't a design pattern. I think the real recommended pattern is that the programmer that adds certain property should take the few moments reasoning whether it is worth exposing and whether it is safe to be exposed. And when removing a property, one should think whether it doesn't break any exsiting client code out there.
Yes, use interfaces. Make sure that the provider of the MBean as well as the consumer uses the smae Java interface.
For the provider part, have a look at how spring can assemble an MBean from an interface.
On the consumer side, it is not very difficult to write an MBean client that takes an interface and translates that into MBean access opertaions.
Related
I have a piece of hardware for which I already have written a small library to provide controls. Previously I used CLI with the program to control the hardware, but now I want to give multiple users access over the network. The control is handled via an object instance, in short, this is non-static and it can't be static as there are runtime configurations as well as important hardware state information to store, but I want to provide control of this hardware to connected sessions. The way I previously had this work was by having my main function set in my serverEndpoint class, and it handled the runtime configuration of the object. This design is messy, and I'd prefer to not organize the code this way, but I've not found any good guides for this elsewhere and I question if perhaps I'm just an atypical use-case or if websockets are the wrong approach, though logically I can't see why that would be. Anyway, my question is how should I provide a handle to this instance to sessions? The hardware control class is already configured to be threadsafe.
Alernatively, my real impetus for reorganizing the code was so that it would be more easily testable, which isn't really possible with the main function located inside the serverEndpoint as far as I'm aware.
I would like to implement custom retry logic for all failed HTTP requests in my Java applications without having to modify all the networking code. Is there a class or interface I can implement that would force all outgoing requests through a method that I could inspect the request and response?
A related example from another project is a custom TrustManager implementation I used to handle revocation status for our internal CA PKI. I'm wondering if there is anything related that could be used to centrally manage HTTP behavior.
You can't do that on the source code level.
You see, the corresponding "data" doesn't "travel" through a specific unique instance of any class. Depending on your protocol, all kinds of classes, such as java.net.Socket will be instantiated over time. You can of course look into what code you wrote is doing, but you have no chance changing the behavior of such existing standard classes on the source code side.
The only things that might help:
looking into debuggers, for example by identifying methods that matter to you, to then set breakpoints there
using instrumentation. Meaning: you hook into JVM startup, and add/manipulate classes at runtime
I am starting to learn about EJB, despite I know they handle the business logic, I don't understand why an EJB has to implement an interface.
I know that the interface is a list of the methods and is used by the client to access them, but what if I don't use an interface?
I know that the no-interface view exist but when should I use an interface then?
could you please explain it using a no IT example? I am taking a course about Java EE 7 and I am stuck in this part, I have read the Oracle tutorial but I've got problems understanding this.
I apologize for my wording mistakes.
thanks in advance
The reason for an interface is because you need to invoke a method in one JVM that transparently can invoke your EJB in another JVM. All the complexity of Java EE come from that it is designed to work across multiple JVMs.
This can be handled in many ways. The approach chosen here is that an interface can make this almost transparent in your code (just compare with invocation through reflection) but the object in the first JVM contains not your code, but instead code that knows how to reach the other JVM and ask it to invoke your method and return the result.
In other words, an interface allows the compiler to help you doing it right in your code, and the application server then provides the magic glue in the object called to reach your EJB.
An EJB doesn't have to implement an interface (anymore). Well, this is only true, if you haven't different VMs accessing the same EJB container. You could host your JBoss in the cloud (e.g.) and have another JEE-Server (e.g. Tomcat) at your company site (or anywhere else) and let the TomEE retrieve its EJB instances from the JBoss Application Server. Then you have to use an interface to program against, since you don't know what the implementation will be.
Since EJB 3 no-interface views are possible. You're free to use interfaces, but you shall be happy if you don't... as long as you dont need distributed EJB-services.
An interface is always a great choice, when you design a big system though. You can easily change you underlying logic if you program against the interface and not the concrete class. So if specifications change, code is much easier to maintain.
I try to build and application based on Java.
For dependency injection I use Google Guice.
Now I came up with the problem of logging some information during the application. I do not talk about general logging in a way of method calls etc. I know about AOP and that I can do like method call tracing etc. with that.
What I look for is manual logging. I need some way of logging in nearly each class in my application. So I thought about two options:
getting the logger by using the Guice injection framework doing this for me through the constructor (or setter or private ...) but it feels like adding the logging concern really to each class and pollutes my constructor
using a global service locator in the method where I want to call the log. Uhh but all DI fans will hate me for doing that
So what is the best way from a practical point of view?
I need some way of logging in nearly each class in my application.
Think again. If you think you need logging in nearly every class, your design might be sub optimal and might cause maintenance issues in the long run. This Stack Overflow answer talks about what's the issue and how to improve it. It's answered in the context of .NET, but the answer is applicable to Java as well.
That answer mainly talks about exception logging, for non-exception logging I would say: Prevent logging too much information at too many places. For each info or warning that you want to log, question whether this shouldn't have been an exception in the first place. For instance, don't log things like "we shouldn't be in this branch", but throw an exception!
And even when you want to log debug information, does anyone ever going to read this? You'll end up with log files with thousands and thousands of lines that nobody ever reads. And if they read it, they have to wade through all those lines of text and do complicated regex searches through it to get the information they were looking for.
Another reason I see developers do this is to cover up for their used coding practices. Just as comments are used in this way. I see developers log things like "we have executed this block" or "this if branch skipped". This way they can trace through the code and big methods.
However, instead of writing big methods, we all know by now that methods should be small. No, even smaller. Besides, if you unit test your code thoroughly, there is not much reason to debug the code and you have verified that it does what it is supposed to do.
And again good design can help here. When you use a design as described in that Stack Overflow answer (with command handlers), you can again create a single decorator that can serialize any arbitrary command message and log it to disk before the execution starts. This gives you an amazingly accurate log. Just add some context information (such as execution time and user name) to the log and you have an audit trail that could even be used to replay commands during debugging or even load testing.
I use this type of application design for a couple of years now, and since then, I hardly ever have any reason to do extra logging within the business logic. It is needed now and then, but those cases are pretty rare.
but it feels like adding the logging concern really to
each class and pollutes my constructor
It does, and you'll end up with constructors with too many parameters. But don't blame the logger, blame your code. You are violating the Single Responsibility Principle here. You can 'hide' this dependency by calling it through a static facade, but that doesn't lower the number of dependencies and overall complexity of a class.
using a global service locator in the method where I want to call the log. Uhh but all DI fans will hate me for doing that
In the end, you will hate yourself for that, because every class is still has an extra dependency (a well hidden dependency in this case). This makes each class more complicated, and will force you to have more code: more code to test, more code to have bugs, more code to maintain.
The topic of logging and how one should go about it is actually a more complex topic than one might at first think.
As with many questions, the answer to how one should approach logging is "It depends". There are certainly some use cases which can be mitigated without the need of components taking on a logging dependency. For example, a need to uniformly log all method calls within a library can be addressed with the Decorator Pattern and superfluous uses of logging exceptions can be addressed by centralizing such logging at the top of a call stack. Such use cases are important to consider, but they don't speak to the essence of the question which really is "When we would like to add detailed logging to a component in strongly-typed languages such as Java and C#, should the dependency be expressed through the component's constructor?"
Use of the Service Locator pattern is considered to be an anti-pattern due to the fact that it's misuse leads to opaque dependencies. That is to say, a component which obtains all its dependencies through a Service Locator doesn't express everything that's needed without knowledge of the internal implementation details. Avoiding the Service Locator pattern is a good rule-of-thumb, but adherents of this rule should understand the when and why so as not to fall into the cargo cult trap.
The goal of avoiding the Service Locator pattern is ultimately to make components easier to use. When constructing a component, we don't want consumers to guess at what is needed for the component to function as expected. Developers using our libraries shouldn't have to look at the implementation details to understand which dependencies are needed for the component to function. In many cases, however, logging is an ancillary and optional concern and serves only to provide tracing information for library maintainers to diagnose issues or to keep an audit log of usage details for which the consumers are neither aware or interested. In cases where consumers of your library must provide dependencies not needed for the primary function of the component, expressing such dependencies as invariant (i.e. constructor parameters) actually negates the very goal sought by avoiding the Service Locator pattern. Additionally, due to the fact that logging is a cross-cutting concern (meaning such needs may be widely desired across many components within a library), injecting logging dependencies through the constructor further amplifies usage difficulty.
Still another consideration is minimizing changes to a library's surface-area API. The surface-area API of your library is any public interfaces or classes required for construction. It's often the case that libraries are constructed through a DI container, particularly for internally-maintained libraries not meant for public consumption. In such cases, registration modules may be supplied by the library for specific DI containers or techniques such as convention-based registration may be employed which hide the top level types, but that doesn't change the fact that they are still part of the surface-area API. A library which can easily be used with a DI container, but can also be used without one is better than one which must be used with a DI container. Even with a DI container, it's often the case with complex libraries to reference implementation types directly for custom registration purposes. If a strategy of injecting optional dependencies is employed, the public interface is changed each time a developer wants to add logging to a new type.
A better approach is to follow the pattern established by most logging libraries such as Serilog, log4net, NLog, etc. and obtain loggers through a logger factory (e.g. Log.ForContext<MyClass>();). This has other benefits as well, such as utilizing filtering capabilities by each respective library. For more discussion on this topic, see this article.
Annotations becoming popular. Spring-3 supports them. CDI depends on them heavily (I can not use CDI with out of annotations, right?)
My question is why?
I heard several issues:
"It helps get rid of XML". But what is bad about xml? Dependencies are declarative by nature, and XML is very good for declarations (and very bad for imperative programming).
With good IDE (like idea) it is very easy to edit and validate xml, is not it?
"In many cases there is only one implementation for each interface". That is not true!
Almost all interfaces in my system has mock implementation for tests.
Any other issues?
And now my pluses for XML:
You can inject anything anywhere (not only code that has annotations)
What should I do if I have several implementations of one interface? Use qualifiers? But it forces my class to know what kind of injection it needs.
It is not good for design.
XML based DI makes my code clear: each class has no idea about injection, so I can configure it and unit-test it in any way.
What do you think?
I can only speak from experience with Guice, but here's my take. The short of it is that annotation-based configuration greatly reduces the amount you have to write to wire an application together and makes it easier to change what depends on what... often without even having to touch the configuration files themselves. It does this by making the most common cases absolutely trivial at the expense of making certain relatively rare cases slightly more difficult to handle.
I think it's a problem to be too dogmatic about having classes have "no idea about injection". There should be no reference to the injection container in the code of a class. I absolutely agree with that. However, we must be clear on one point: annotations are not code. By themselves, they change nothing about how a class behaves... you can still create an instance of a class with annotations as if they were not there at all. So you can stop using a DI container completely and leave the annotations there and there will be no problem whatsoever.
When you choose not to provide metadata hints about injection within a class (i.e. annotations), you are throwing away a valuable source of information on what dependencies that class requires. You are forced to either repeat that information elsewhere (in XML, say) or to rely on unreliable magic like autowiring which can lead to unexpected issues.
To address some of your specific questions:
It helps get rid of XML
Many things are bad about XML configuration.
It's terribly verbose.
It isn't type-safe without special tools.
It mandates the use of string identifiers. Again, not safe without special tool support.
Doesn't take any advantage of the features of the language, requiring all kinds of ugly constructs to do what could be done with a simple method in code.
That said, I know a lot of people have been using XML for long enough that they are convinced that it is just fine and I don't really expect to change their minds.
In many cases there is only one implementation for each interface
There is often only one implementation of each interface for a single configuration of an application (e.g. production). The point is that when starting up your application, you typically only need to bind an interface to a single implementation. It may then be used in many other components. With XML configuration, you have to tell every component that uses that interface to use this one particular binding of that interface (or "bean" if you like). With annotation-based configuration, you just declare the binding once and everything else is taken care of automatically. This is very significant, and dramatically reduces the amount of configuration you have to write. It also means that when you add a new dependency to a component, you often don't have to change anything about your configuration at all!
That you have mock implementations of some interface is irrelevant. In unit tests you typically just create the mock and pass it in yourself... it's unrelated to configuration. If you set up a full system for integration tests with certain interfaces using mocks instead... that doesn't change anything. For the integration test run of the system, you're still only using 1 implementation and you only have to configure that once.
XML: You can inject anything anywhere
You can do this easily in Guice and I imagine you can in CDI too. So it's not like you're absolutely prevented from doing this by using an annotation-based configuration system. That said, I'd venture to say that the majority of injected classes in the majority of applications are classes that you can add an #Inject to yourself if it isn't already there. The existence of a lightweight standard Java library for annotations (JSR-330) makes it even easier for more libraries and frameworks to provide components with an #Inject annotated constructor in the future, too.
More than one implementation of an interface
Qualifiers are one solution to this, and in most cases should be just fine. However, in some cases you do want to do something where using a qualifier on a parameter in a particular injected class would not work... often because you want to have multiple instances of that class, each using a different interface implementation or instance. Guice solves this with something called PrivateModules. I don't know what CDI offers in this regard. But again, this is a case that is in the minority and it's not worth making the rest of your configuration suffer for it as long as you can handle it.
I have the following principle: configuration-related beans are defined with XML. Everything else - with annotations.
Why? Because you don't want to change configuration in classes. On the other hand, it's much simpler to write #Service and #Inject, in the class that you want to enable.
This does not interfere with testing in any way - annotations are only metadata that is parsed by the container. If you like, you can set different dependencies.
As for CDI - it has an extension for XML configuration, but you are right it uses mainly annotations. That's something I don't particularly like in it though.
In my opinion, this is more a matter of taste.
1) In our project (using Spring 3), we want the XML-configuration files to be just that: configuration. If it doesn't need to be configured (from end-user perspective) or some other issue doesn't force it to be done in xml, don't put the bean-definitions/wirings into the XML-configurations, use #Autowired and such.
2) With Spring, you can use #Qualifier to match a certain implementation of the interface, if multiple exist. Yes, this means you have to name the actual implementations, but I don't mind.
In our case, using XML for handling all the DI would bloat the XML-configuration files a lot, although it could be done in a separate xml-file (or files), so it's not that valid point ;). As I said, it's a matter of taste and I just think it's easier and more clean to handle the injections via annotations (you can see what services/repositories/whatever something uses just by looking at the class instead of going through the XML-file looking for the bean-declaration).
Edit: Here's an opinion about #Autowired vs. XML that I completely agree with: Spring #Autowired usage
I like to keep my code clear, as you pointed. XML feets better, at least for me, in the IOC principle.
The fundamental principle of Dependency Injection for configuration is that application objects should not be responsible for looking up the resources or collaborators they depend on. Instead, an IoC container should configure the objects, externalizing resource lookup from application code into the container. (J2EE Development without EJB - Rod Johnson - page 131)
Again, it just my point of view, no fundamentalism in there :)
EDIT: Some useful discussions out there:
http://forum.springsource.org/showthread.php?t=95126
http://www.theserverside.com/discussions/thread.tss?thread_id=61217
"But what is bad about xml?" It's yet another file to manage and yet another place to have to go look for a bug. If your annotations are right next to your code it's much easier to mange and debug.
Like all things, dependency injection should be used in moderation. Moreover, all trappings of the injections should be segregated from the application code and relegated to the code associated with main.
In general applications should have a boundary that separates the abstract application code from the concrete implementation details. All the source code dependencies that cross that boundary should point towards the application. I call the concrete side of that boundary, the main partition, because that's where 'main' (or it's equivalent) should live.
The main partition consists of factory implementations, strategy implementations, etc. And it is on this side of the boundary that the dependency injection framework should do it's work. Then those injected dependencies can be passed across the boundary into the application by normal means. (e.g. as arguments).
The number of injected dependencies should be relatively small. A dozen or less. In which case, the decision between XML or annotations is moot.
Also don't forget Spring JavaConfig.
In my case the developers writing the application are different that the ones configuring it (different departments, different technologies/languages) and the last group doesn't even has access to the source code (which is the case in many enterprise setups). That makes Guice unusable since I would have to expose source code rather than consuming the xmls configured by the developers implementing the app.
Overall I think it is important to recognize that providing the components and assembling/configuring an application are two different exercises and provide if needed this separation of concerns.
I just have a couple of things to add to what's already here.
To me, DI configuration is code. I would like to treat it as such, but the very nature of XML prevents this without extra tooling.
Spring JavaConfig is a major step forward in this regard, but it still has complications. Component scanning, auto-magic selection of interface implementations, and semantics around CGLIB interception of #Configuration annotated classes make it more complex than it needs to be. But it's still a step forward from XML.
The benefit of separating IoC metadata from application objects is overstated, especially with Spring. Perhaps if you confined yourself to the Spring IoC container only, this would be true. But Spring offers a wide application stack built on the IoC container (Security, Web MVC, etc). As soon as you leverage any of that, you're tied to the container anyway.
XML has the only benefit of a declarative style that is defined clearly separated from the application code itself. That stays independent from DI concerns. The downsides are verbosity, poor re-factoring robustness and a general runtime failure behaviour. There is just a general (XML) tool support with little benefit compared to IDE support for e.g. Java. Besides this XML comes with a performance overhead so it usually is slower than code solutions.
Annoations often said to be more intuitive and robust when re-factoring application code. Also they benefit from a better IDE guidance like guice provides. But they mix application code with DI concerns. An application gets dependent on a framework. Clear separation is almost impossible. Annotations are also limited when describing different injection behaviour at the same place (constructor, field) dependent on other circumstances (e.g. robot legs problem). Moreover they don't allow to treat external classes (library code) like your own source. Therefore they are considered to run faster than XML.
Both techniques have serious downsides. Therefore I recommend to use Silk DI. It is declarative defined in code (great IDE support) but 100% separated from your application code (no framework dependency). It allows to treat all code the same no matter if it is from your source or a external library. Problems like the robot legs problem are easy to solve with usual bindings. Furthermore it has good support to adapt it to your needs.