Transaction configuration for Spring Java configured context - java

I've been struggling with this for a few hours now.
I'm trying to migrate my Spring XML configuration to a full Java based configuration.
I'm using AnnotationConfigApplicationContext as a context implementation.
I'm having trouble finding an Java equivalent for this line, from my old XML configuration:
<tx:annotation-driven transaction-manager="transactionManager" />
As a result, Spring doesn't manage the transactions.
In my Java configuration I have initialized the relevant beans for transactions: the session factory, the transactional manager, etc, but without that line, no transaction proxy is used, so no transactions are actually in place.
So my question is how do I either translate that line to my Java context configuration or how to I go about solving the problem in another way.
Any help is appreciated.
Thanks.

You can now use #EnableTransactionManagement.
See: http://blog.springsource.com/2011/06/10/spring-3-1-m2-configuration-enhancements/

In my experience, it's not practical to entirely replace the XML config with #Bean-style config. Some things do make more sense configured in java, specifically your own bean definitions. But when it comes to infrastructural-type declarations like <tx:annotation-driven>, the XML syntax is a lot more concise.
You can reproduce the same effect in pure java, but it ends up being cumbersome and unintuitive, since things like <tx:annotation-driven> are typically interactions of complex low-level Spring infrastructure classes that you really don't want to touch.
My advice - mix and match, using each of Java and XML for their own strengths. This is quite easy to do. I prefer to keep the normal XML ApplicationContext classes, and then declare my #Configuration classes as beans in that XML context, alongside things like <tx:annotation-driven>.

Take a look at https://spring.io/blog/2011/02/17/spring-3-1-m1-introducing-featurespecification-support. Spring 3.1's FeatureSpecification classes such as TxAnnotationDriven are designed to solve exactly the problem described above.

Related

Why Java Config is favorable in spring boot when compared to XML config?

I am new to spring-boot. I am building a rest based application using spring-boot and was working on setting up security using spring-security. It is my understnading that I can setup spring-security with either xml config or with Java config.
However, I found the following in spring-boot documentation. https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-configuration-classes.html
It is in favor of using Java Config as opposed to XML config. Changes in Java config requires recompilation. Yet, it makes me think why the documentation favors Java Config.
Configuration classes Spring Boot favors Java-based configuration. Although it is possible to call SpringApplication.run() with an XML
source, we generally recommend that your primary source is a
#Configuration class. Usually the class that defines the main method
is also a good candidate as the primary #Configuration.
Many Spring configuration examples have been published on the Internet
that use XML configuration. Always try to use the equivalent
Java-based configuration if possible. Searching for Enable*
annotations can be a good starting point.
15.1 Importing additional configuration classes You don’t need to put all your #Configuration into a single class. The #Import annotation
can be used to import additional configuration classes. Alternatively,
you can use #ComponentScan to automatically pick up all Spring
components, including #Configuration classes.
15.2 Importing XML configuration If you absolutely must use XML based configuration, we recommend that you still start with a #Configuration
class. You can then use an additional #ImportResource annotation to
load XML configuration files.
There are some advantages
Java is type safe. Compiler will report issues if you are configuring right bean class qualifiers.
XML based on configuration can quickly grow big. [Yes we can split and import but still
Search is much simpler, refactoring will be bliss. Finding a bean definition will be far easier.
There are still people who like XML configuration and continue to do it.
For more info you can refer Java configuration advantages Some more reasons

Java based dependency injection in Spring

I'm working in a webapp and this is the first time that I'm using Java based configuration. I have a bunch of class to configure all:
ApplicationContext
PersistenceContext
SecurityContext
WebAppInitializer
WebMvcContext
Now I'm defining Spring Data repositories and the service layer so I need to inject the repositories there. Normally I would use Autowired but I've read that it is preferable to define the injections manually so the question is, where?
Maybe neither of the previous configuration classes is suitable for such task but, do I have to create a single class to define all the injections or is better to have on for each function? What happens if the project grows too much?
I think that the main question would be what is best way to organize dependencies in a Spring project. What do you do?
I add here an image of the structure of the project as a petition. I'm trying to decouple layers and now I need to inject UserRepository to UserService.
No, I would not define a single class to do all the injections. All your classes are coupled that way.
I don't understand what "define the injections manually" means. You have to specify them in either XML or annotations. There's no other way that I know of.
You don't say if you're using XML or annotation configuration. I find myself using the latter more of the time, with only enough XML configuration to tell the Spring app context to scan for annotations.
The Spring idiom would have you specify your configuration in layers if you're using XML. It's a moot point for annotations, because they go into your source code.
Your application will read the Spring context on start up, instantiate all the beans, and wire together the necessary dependencies. You're good to go from then on.
I disagree with the link you provided. Avoid autowiring? No.
The article said that he recommends using XML configuration for large projects. This is a very small project at this point. It seems to me that auto wiring with annotations would be fine even by the article's author's words.

Why Spring MVC configuration support for XML configuration is deprecated?

Spring MVC uses mainly annotations to configure its Controllers, as far as I know, the only way to configure a Controller in Spring WITHOUT Annotions (only XML) is extending the AbstracController (or Similar Controller classes) and currently all this classes are deprecated for Spring 3.
While I think that is a good idea to drop support for this classes, mainly because extending this classes creates controllers that hardly depend of Spring as a dependency, I don't understand why Spring doesn't provides a configuration like Struts Actions (Actions in Struts 2 don't extend any weird class so they dont' have any dependency of Struts)
Why Spring MVC doesnt provide a clean POJO-style configuration like Struts 2 Actions via XML?
Why to drop support for XML configuration on MVC using ugly Annotations? why not to drop it in ALL Spring Proyects?
The main problem with the XML/POJO approach is that there is no way to tell from looking at your code that special magic is going on.
Instead of seeing
#SomeAnnotation <<-- Oh, golly there is something special happening here.
java code...
You see
Java code <<-- special magic hidden in XML file (or not, no way to tell)
<<-- are these linked? no idea..
<<-- is something going on? let me go and search....
If changes happen to the source code, the XML may (or may not be) out of sync.
With the annotations you can update the java code and the spring annotations at the same time.
Yes it's cluttered but at least it's easy to sync the two.
Annotations are hard enough to grok when they're in your face. If they're not even visible the mental burden for us non-angry developers is really too much to bear.
why not to drop it in ALL Spring Projects?
Wouldn't that be sweet....
using ugly Annotations?
Obviously the question has been asked: Is there a way to hide annotations in Eclipse?
And the answer is: https://stackoverflow.com/a/2569646/650492
Sort of... does that help?

Can I use Spring without annotations at all only through xmls?

I have a web application using spring annotations extensively. Can I switch back from spring annotations to xml configuration files? Encluding controllers,..etc. I need examples of the configuration files please.
Yes you can switch to externalize the configuration using xml's. Initially only xml's were supported by spring. You can get examples from their reference manual.
If you are looking for complete examples then www.springbyexample.org
Yes. Spring supports annotations, configuration classes and xml configuration. It was never the goal of annotations to deprecate the xml configuration, and it is still fully supported today.
At the S2G forum in Amsterdam last year, it was specifically stated that the goal remains for both approaches to be completely equivalent.
As for the details on how to do it, the documentation of Spring is very good. I suggest you start there. Check out the pet store example, and read up on ContextLoaderListener. It should get you started.
Yes, you can switch back and forth to XML and annotations. In fact, if you even need, you can use a combination of both. Additionally, depending on the type of control you are trying to extract from XML configuration, you can also use #Configuration annotations which provides a way of producing XML configuration via Java code. Keep in mind, however, that there are a few obscure configuration constructs that are not representable by any annotations and can only be done via XML files.

Is fine grained control of aspectj-autoproxy possible in spring?

If I just add <aop:aspectj-autoproxy proxy-target-class="false"/> to the start of my spring context, every single bean that implements an interface gets a JDK proxy. I would really like to limit the proxying A) to classes that actually need proxies or B) classes that I specify as needing proxies.
I tried using the aop:scoped-proxy stanza within an xml bean defintion for the beans that need proxies, but it turns out this does not seem to give me aop-advice.
I also tried adding <aop:aspectj-autoproxy ....> near the end of my spring xml file, but before adding all the beans that need proxies, but it does not seem to work properly.
I have a lot of beans with interfaces but only a (well defined) handful need AoP advice, and those proxies are messing up my stacktraces big time. (I have peeked at spring 3.0 and suspect it's going to be possible there but it seems like it's a while away).
Is this possible in 2.5.X ?
As can be seen in AbstractAdvisorAutoProxyCreator.java line 67 (Spring 2.5.6), the autoproxy creator really only does what I ask it to. It does not autoproxy more than it thinks necessary.
It turns out it's the kind of pointcut expression you use greatly influences how much proxying this class does; the annotation I was using was
#Around(value="#target(myannotation)")
This basically means spring generates a proxy that decides to intercept based on the type of the actual invocation target. The downside of this is that spring tries to do this with all available beans in the applicationcontext. If I'd been using something like#within instead, spring would be using the interface to decide if autoproxying should take place, and this can statically be determined at the time the applicationcontext is built.
So now I only have two classes that are proxied ;)

Categories

Resources