JSR-299 (CDI) configuration at runtime - java

I need to configure different #Alternatives, #Decorators and #Injectors for different runtime environments (think testing, staging and production servers).
Right now I use maven to create three wars, and the only difference between those wars are in the beans.xml files. Is there a better way to do this? I do have #Alternative #Stereotypes for the different environments, but even then I need to alter beans.xml, and they don't work for #Decorators (or do they?)
Is it somehow possible to instruct CDI to ignore the values in beans.xml and use a custom configuration source? Because then I could for example read a system property or other environment variable.
The application exclusively runs in containers that use Weld, so a weld-specific solution would be ok.
I already tried to google this but can't seem to find good search terms, and I asked the Weld-Users-Forums, but to no avail. Someone over there suggested to write my own custom extension, but I can't find any API to actually change the container configuration at runtime.
I think it would be possible to have some sort of #ApplicationScoped configuration bean and inject that into all #Decorators which could then decide themselves whether they should be active or not and then in order to configure #Alternatives write #Produces methods for every interface with multiple implementations and inject the config bean there too.
But this seems to me like a lot of unnecessary work to essentially duplicate functionality already present in CDI?
edit
Ok, I realized I'm a bit stupid... of course it is possible to add stereotypes and inteceptors at runtime using the CDI extension API:
void beforeBeanDiscovery(#Observes BeforeBeanDiscovery bbd) {
bbd.addInterceptorBinding(...)
bbd.addStereotype(...)
}
But what I didn't find was an API to add a decorator. The only thing I found was to activate all #Decorators in the beans.xml, then observe
public <T> void processAnotated(#Observes ProcessAnnotatedType<T> event)
and call
event.veto()
if I don't want a #Decorator to be active.

You might want to take a look at JBoss Seam, specifically the Solder sub-project.
It allows dependency driven CDI resolution, so that certain beans are only available if other beans or resources are available. (Class A if "dataSource" is available, Class B if "entityManager" is available)
Since it's open source, you can also take a look at how they wired that together, and use that knowledge as a basis for writing your own extension if needed.
If you're using JSF, I would highly recommend using SEAM-JSF as well, as it gets rid of the clunkiness of having two injection frameworks (JSF DI/CDI) and allows CDI beans in JSF scopes.

Related

Dynamically adding beans and jars to Java application

For an ongoing project, we are looking for a possibility to dynamically download and load jar files into a running application. Apart from downloading the files (which is probably fairly straightforward), I am unaware of any solution that would automatically add the jar's to the classpath, and do discovery of the annotations (like CDI beans).
Given such a system, it would be rather handy if the #Inject annotation would not throw a runtime failure of an implementation of a class is not present (because that module-jar was not loaded).
Is there currently any such system? Does spring or OSGi fit this need?
Any ideas how close project Jigsaw would come in trying to fulfill this on application level?
I think you need OSGI, using an OSGI container like Karaf : https://karaf.apache.org
In standard java provide ServiceLoader https://docs.oracle.com/javase/tutorial/ext/basics/spi.html
I advice you to not follow that path
It should be possible to dynamically load jar files without the usage of OGSI. The keyword are Classloaders especially when used with a proper hierarchy. The following answer should give you an idea: How should I load Jars dynamically at runtime? but keep in mind that this might cause serious security issues
You followed the path at 2. even I advice you not to do it. But now you end up in the scenario that the context of your used framework does not know this classes. You would have this problem with most IOC frameworks. Since they build up the context on startup. There are libraries for this created for development purpose (spring-loaded, spring dev tools, JRebel). If your IOC framework supports it go with it.
Regarding handling not available jars. The best point to do research on this is Spring Boot and its auto configuration mechanism. It checks if certain classes/jars (not sure to be honest) are available and add additional behavior for this cases. But still this is application startup solution and not a runtime IOC solution.

Determine whether class is an EJB or not - bytecode analysis

I am working on a bytecode analysis project. I am using ASM library for the same. For one of the requirement, I need to determine whether .class is a EJB or Non-EJB. Since EJB has various versions, we are trying to write logic as fool proof as possible and question may feel strange. I am well aware it may not be possible to automate completely. I am trying to follow roughly these steps:
For EJB 2.x
First check if class extends a specific interface like EJBHome, EJBLocalHome etc
Check if it has a specific methods like ejbActivate(), ejbPassivate(),ejbRemove()
To check if it is a session bean, check if it implements SessionBean interface.
etc, etc
For EJB 3.x
I think EJB 3.x is easier compared to EJB 2.x generations because of annotations.
I can check annotations like #Stateless to check if it is a stateless bean
Check annotation #Stateful to check if it is a stateful bean.
Or check if #Remote annotation exists
etc etc..
These are the some of the ways I am thinking to check if .class is an EJB or not. My question is, is there any other way to check if any class is an EJB, I mean am I missing any important thing? Please be aware that I don't have much experience in EJB.
Also is there any chance that ASM library provides this option?

Calling of <aop:aspectj-autoproxy /> multiple times when loading spring context

Let's say I am defining a custom aspect and to enable proxying I am using aop:aspectj-autoproxy. Now I am also importing another third-party spring context in the application that also happens to call aop:aspectj-autoproxy (ofcourse I won't know about it upfront unless I pore over the context xml contents extracted from the JAR). Potentially there can be many such contexts. Here I see that the beans matching the pointcut get proxied over and over i.e. proxy of a proxy. Is there a way that one can avoid such a proxy of a proxy? Also feel free to point out any anti-patterns that may be at play here.
Thanks in advance.
From Spring documentation:
http://static.springsource.org/spring/docs/3.0.6.RELEASE/spring-framework-reference/html/aop.html#aop-proxying
Note Multiple sections are collapsed into a single
unified auto-proxy creator at runtime, which applies the strongest
proxy settings that any of the sections (typically from
different XML bean definition files) specified. This also applies to
the tx:annotation-driven and aop:aspectj-autoproxy elements.
To be clear: using 'proxy-target-class="true"' on
, or
elements will force the use of CGLIB proxies for all three of them
I believe the problem mainly relates to
Now I am also importing another third-party spring context in the application that also happens to call aop:aspectj-autoproxy
Instead of directly importing the app ctx provided by 3rd party lib (which is, in most case, provided for ease of initial development or for small project), try to manage those 3rd party beans in your own app ctx, and make sure you do not have multiple aop:aspectj-autoproxy (There are lots of bean post-processor etc in spring that is not safe in multiple declaration.)

Spring, #Autowired, #Resource and <property>

This week I've been trying to learn Spring, JBoss, Maven, JPA and Hibernate and I've had a lot of fun with it. I am somewhat confused over the many different ways to inject resources in a class though. Until this week I was not even aware that you could inject resources in any other way than using the <property> tag in your Spring XML configuration.
<bean id="catalogService" class="com.idbs.omics.catalog.service.CatalogService">
<property name="termDao" ref="termDao"></property>
</bean>
When I started experimenting with JPA I encountered #PersistenceContext, but that seems to be a special case so fair enough. Then I started reading up on Spring's testing framework and I saw the first example that used #Resource(name="catalogService") and then in a Web Service example #Autowired crashed the party!
**The Question!**
So what is the difference between all these and is there right and wrong situation to use them in? I guess I'm looking for a best practice here.
Cheers all
#Autowired, #Resource and #Inject
I think the part of the Spring Reference that you need to read is
3.9 Annotation-based container configuration
There are many sets of similar annotations. Often, there is a Spring and a non-Spring version that do the same thing. Spring tries to embrace standards whenever they are available, but often the Spring guys came up with their own ideas before a standard appeared. Example: Spring supports its own #Autowired annotation, but also the new #Inject annotation from JSR-330, as well as the JSR-250 #Resource annotation (all of which can be used to do the same thing).
The key concept here is that Spring doesn't force you to use its own code, but supports many different ways without coupling your application to Spring. (There are still a few annotations that have no non-Spring equivalent, like #Transactional, but if you want to, you can add that functionality via XML instead, so you can keep your application 100% Spring free and still use many convenience annotations and of course Spring wiring and lifecycle management behind the scenes.
The other aspect of this is when to use annotations and when to use XML spring wiring files.
My view is that this is a trade-off between code readability and the ability to reconfigure.
If you use annotations, then you can see from just the source code what is wired to what. By contrast, if you use XML wiring files, you have two places to look.
If you use XML wiring files, you can make configuration changes by modifying (or with Maven overlaying) the XML wiring files. If you are bold, you can even do this on a deployed webapp. By contrast, changing the IoC wirings when annotations are used requires you to modify the Java files and recompile.
(Aside: in the case of the second bullet, the ideal situation would be to have a nice GUI-based tool for reconfiguring the wirings that could be run in either your development sandbox, or the deployed webapp folder. Does anyone know of such a tool?)

Xml configuration versus Annotation based configuration [closed]

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 8 years ago.
Improve this question
In a few large projects i have been working on lately it seems to become increasingly important to choose one or the other (XML or Annotation). As projects grow, consistency is very important for maintainability.
My questions are: what are the advantages of XML-based configuration over Annotation-based configuration and what are the advantages of Annotation-based configuration over XML-based configuration?
Annotations have their use, but they are not the one silver bullet to kill XML configuration. I recommend mixing the two!
For instance, if using Spring, it is entirely intuitive to use XML for the dependency injection portion of your application. This gets the code's dependencies away from the code which will be using it, by contrast, using some sort of annotation in the code that needs the dependencies makes the code aware of this automatic configuration.
However, instead of using XML for transactional management, marking a method as transactional with an annotation makes perfect sense, since this is information a programmer would probably wish to know. But that an interface is going to be injected as a SubtypeY instead of a SubtypeX should not be included in the class, because if now you wish to inject SubtypeX, you have to change your code, whereas you had an interface contract before anyways, so with XML, you would just need to change the XML mappings and it is fairly quick and painless to do so.
I haven't used JPA annotations, so I don't know how good they are, but I would argue that leaving the mapping of beans to the database in XML is also good, as the object shouldn't care where its information came from, it should just care what it can do with its information. But if you like JPA (I don't have any expirience with it), by all means, go for it.
In general:
If an annotation provides functionality and acts as a comment in and of itself, and doesn't tie the code down to some specific process in order to function normally without this annotation, then go for annotations. For example, a transactional method marked as being transactional does not kill its operating logic, and serves as a good code-level comment as well. Otherwise, this information is probably best expressed as XML, because although it will eventually affect how the code operates, it won't change the main functionality of the code, and hence doesn't belong in the source files.
There is a wider issue here, that of externalised vs inlined meta-data. If your object model is only ever going to persisted in one way, then inlined meta-data (i.e. annotations) are more compact and readable.
If, however, your object model was reused in different applications in such a way that each application wanted to persist the model in different ways, then externalising the meta-data (i.e. XML descriptors) becomes more appropriate.
Neither one is better, and so both are supported, although annotations are more fashionable. As a result, new hair-on-fire frameworks like JPA tend to put more emphasis on them. More mature APIs like native Hibernate offer both, because it's known that neither one is enough.
I always think about annotations as some kind of indicator of what a class is capable of, or how it interacts with others.
Spring XML configuration on the other hand to me is just that, configuration
For instance, information about the ip and port of a proxy, is definetly going into an XML file, it is the runtime configuration.
Using #Autowire,#Element to indicate the framework what to do with the class is good use of annotations.
Putting the URL into the #Webservice annotation is bad style.
But this is just my opinion.
The line between interaction and configuration is not always clear.
I've been using Spring for a few years now and the amount of XML that was required was definitely getting tedious. Between the new XML schemas and annotation support in Spring 2.5 I usually do these things:
Using "component-scan" to autoload classes which use #Repository, #Service or #Component. I usually give every bean a name and then wire them together using #Resource. I find that this plumbing doesn't change very often so annotations make sense.
Using the "aop" namespace for all AOP. This really works great. I still use it for transactions too because putting #Transactional all over the place is kind of a drag. You can create named pointcuts for methods on any service or repository and very quickly apply the advice.
I use LocalContainerEntityManagerFactoryBean along with HibernateJpaVendorAdapter to configure Hibernate. This lets Hibernate easily auto-discover #Entity classes on the classpath. Then I create a named SessionFactory bean using "factory-bean" and "factory-method" referring to the LCEMFB.
An important part in using an annotation-only approach is that the concept of a "bean name" more or less goes away (becomes insignificant).
The "bean names" in Spring form an additional level of abstraction over the implementing classes. With XML beans are defined and referenced relative to their bean name. With annotations they are referenced by their class/interface. (Although the bean name exists, you do not need to know it)
I strongly believe that getting rid of superfluous abstractions simplifies systems and improves productivity. For large projects I think the gains by getting rid of XML can be substantial.
It depends on what everything you want to configure, because there are some options that cannot be configured with anotations. If we see it from the side of annotations:
plus: annotations are less talky
minus: annotations are less visible
It's up to you what is more important...
In general I would recommend to choose one way and use it all over some closed part of product...
(with some exceptions: eg if you choose XML based configurations, it's ok to use #Autowire annotation. It's mixing, but this one helps both readability and maintainability)
I think that visibility is a big win with an XML based approach. I find that the XML isn't really that bad, given the various tools out there for navigating XML documents (i.e. Visual Studio + ReSharper's File Structure window).
You can certainly take a mixed approach, but that seems dangerous to me if only because, potentially, it would make it difficult for new developers on a project to figure out where different objects are configured or mapped.
I don't know; in the end XML Hell doesn't seem all that bad to me.
There are other aspect to compare like refactoring and other code changes. when using XML it takes serous effort to make refactoring because you have to take care of all the XML content. But it is easy when using Annotations.
My preferred way is the Java based configuration without (or minimal) annotations. http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-java
I might be wrong, but I thought Annotations (as in Java's #Tag and C#'s [Attribute]) were a compile-time option, and XML was a run-time option. That to me says the are not equivalent and have different pros and cons.
I also think a mix is the best thing, but it also depends on the type of configuration parameters.
I'm working on a Seam project which also uses Spring and I usually deploy it to different development and test servers. So I have split:
Server specific configuration (Like absolute paths to resources on server): Spring XML file
Injecting beans as members of other beans (or reusing a Spring XML defined value in many beans): Annotations
The key difference is that you don't have to recompile the code for all changing server-specific configurations, just edit the xml file.
There's also the advantage that some configuration changes can be done by team members who don't understand all the code involved.
In the scope of DI container, I consider annotation based DI is abusing the use of Java annotation. By saying that, I don't recommend to use it widely in your project. If your project does really needs the power of DI container, I would recommend to use Spring IoC with Xml based configuration option.
If it is just for a sake of Unit-test, developers should apply Dependency Inject pattern in their coding and take advantages from mocking tools such as EasyMock or JMock to circumvent dependencies.
You should try to avoid using DI container in its wrong context.
Configuration information that is always going to be linked to a specific Java component (class, method, or field) is a good candidate to be represented by annotations. Annotations work especially well in this case when the configuration is core to the purpose of the code. Because of the limitations on annotations, it's also best when each component can only ever have one configuration. If you need to deal with multiple configurations, especially ones that are conditional on anything outside the Java class containing an annotation, annotations may create more problems than they solve. Finally, annotations cannot be modified without recompiling the Java source code, so anything that needs to be reconfigurable at run time can't use annotations.
Please refer following links. They might be useful too.
Annotations vs XML, advantages and disadvantages
http://www.ibm.com/developerworks/library/j-cwt08025/
This is the classic 'Configuration versus Convention' question. Personal taste dictates the answer in most cases. However, personally I prefer Configuration (i.e. XML based) over Convention. IMO IDE's are sufficiently robust enough to overcome some of the XML hell people often associate w/ the building and maintaining an XML based approach. In the end, I find the benefits of Configuration (such as building utilities to build, maintain and deploy the XML config file) outweighs Convention in the long run.
I use both. Mostly XML, but when I have a bunch of beans that inherit from a common class and have common properties, I use annotations for those, in the superclass, so I don't have to set the same properties for each bean. Because I'm a bit of a control freak, I use #Resource(name="referredBean") instead of just autowiring stuff (and save myself a lot of trouble if I ever need another bean of the same class as the original referredBean).
There are some pros and cons of annotation configuration from my experience:
When it comes to JPA configuration since it is done once and usually are not changed quite often I prefer to stick to annotation configuration. There maybe a concern regarding possibility to see a bigger picture of configuration - in this case I use MSQLWorkbench diagrams.
Xml configuration is very good to get a bigger picture of application but it maybe cumbersome to find some errors until runtime. In this case Spring #Configuration annotation sounds as a better choice since it let you see a bigger picture as well and also allows to validate configuration on compile time.
As for Spring configuration I prefer to combine both approaches: use #Configuration annotation with Services and Query interfaces and xml configuration for dataSource and spring configuration stuff like context:component-scan base-package="..."
But xml configuration bits java annotations when it comes to flow configuration(Spring Web Flow or Lexaden Web Flow) since it is extremely important to see a bigger picture of the whole business process. And it sounds cumbersome to have it implemented with annotations approach.
I prefer combining both approaches - java annotations and essential xml minimum that minimize configuration hell.
For Spring Framework I like the idea of being able to use the #Component annotation and setting the "component-scan" option so that Spring can find my java beans so that I do not have to define all of my beans in XML, nor in JavaConfig. For example, for stateless singleton java beans that simply need to be wired up to other classes (via an interface ideally) this approach works very well. In general, for Spring beans I have for the most part moved away from Spring XML DSL for defining beans, and now favor the use of JavaConfig and Spring Annotations because you get some compile time checking of your configuration and some refactoring support that you don't get with Spring XML configuration. I do mix the two in certain rare cases where I've found that JavaConfig/Annotations can't do what is available using XML configuration.
For Hibernate ORM (haven't used JPA yet) I still prefer the XML mapping files because annotations in domain model classes to some degree violates The Clean Architecture which is a layering architectural style I have adopted over the past few years. The violation occurs because it requires the Core Layer to depend on persistence related things such as Hibernate or JPA libraries and it makes the domain model POJOs a bit less persistence ignorant. In fact the Core Layer is not supposed to depend on any other infrastructure at all.
However, if The Clean Architecture is not your "cup of tea" then I can see there are definitely advantages (such as convenience and maintainability) of using Hibernate/JPA annotations in domain model classes over separate XML mapping files.

Categories